package com.eco.fanliapp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eco.fanliapp.common.constant.ApiEnum;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.*;
import com.eco.fanliapp.dataoke.DaTaoKeConfig;
import com.eco.fanliapp.dataoke.DaTaoKeItemInfoService;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.taobao.ItemInfoController;
import com.eco.fanliapp.taobao.SearchController;
import com.eco.fanliapp.taobao.SessionController;
import com.eco.fanliapp.taobao.TklController;
import com.eco.fanliapp.utils.*;
import com.eco.fanliapp.vo.*;
import com.eco.fanliapp.vo.HaoDanKuHotKeyInfo.KeyWord;
import com.eco.fanliapp.vo.HaoDanKuSuperClassifyInfo.GeneralClassify;
import com.eco.fanliapp.vo.TbkItemConvertInfo.TbkItemConvertData;
import com.eco.fanliapp.vo.TbkItemInfoGetInfo.NTbkItem;
import com.eco.fanliapp.vo.TbkPrivilegeGetInfo.TbkPrivilege;
import com.eco.fanliapp.vo.TbkScMaterialOptionalInfo.MapData;
import com.eco.fanliapp.vo.respone.DTKResponse;
import com.eco.fanliapp.vo.respone.ResponeFriendsResults;
import com.eco.fanliapp.vo.respone.ResponeOrderResults.OrderDataBean;
import com.eco.fanliapp.vo.respone.ResponeResults;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TbkDgOptimusMaterialRequest;
import com.taobao.api.response.*;
import com.taobao.api.response.TbkScPublisherInfoSaveResponse.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 淘宝实现类
 *
 * @author xiaoxx
 */
@Service
@Slf4j
public class TaoBaoServiceImpl implements ITaoBaoService {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    private IAppGoodsClassifyService iAppGoodsClassifyService;
    @Autowired
    private IAppUserService iAppUserService;
    @Autowired
    private ITaoBaoMethodService taoBaoMethodService;
    @Autowired
    private IWebCircleFriendsService iWebCircleFriendsService;
    @Lazy
    @Autowired
    private IAppGoodsService iAppGoodsService;
    @Autowired
    private IUserCashschemeService iUserCashschemeService;
    @Autowired
    private IGoodsFreeService iGoodsFreeService;
    @Autowired
    private SessionController sessionController;
    @Autowired
    private ItemInfoController itemInfoController;
    @Autowired
    private SearchController searchController;
    @Autowired
    private TklController tklController;
    @Autowired
    private IAppCompanyService appCompanyService;
    @Autowired
    private IAppCompanyService iAppCompanyService;
    @Autowired
    private AppUserMapper appUserMapper;
    @Autowired
    private DaTaoKeItemInfoService daTaoKeItemInfoService;
    @Autowired
    private AppGoodsMapper appGoodsMapper;

    @Autowired
    private ISyLabelTypeService syLabelTypeService;
    @Autowired
    private ISyLabelGoodsService iSyLabelGoodsService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ITaobaoSchemeService iTaobaoSchemeService;
    @Autowired
    private SyTljGoodsfreeMapper iSyTljGoodsfreeMapper;

    @Autowired
    private RedisTemplateService redisTemplateService;
    @Autowired
    private ISyChannelGoodsService syChannelGoodsService;
    @Autowired
    private IAppGeneralfeeschemeService appGeneralfeeschemeService;
    @Autowired
    private AppUserOrderMapper appUserOrderMapper;
    @Autowired
    private GoodsFreeIntegralMapper goodsFreeIntegralMapper;
    @Autowired
    private IGoodsImageLableService goodsImageLableService;

    @Autowired
    private ITaoBaoService taoBaoService;

    /**
     * API
     * 根据关键字获取商品信息列表
     *
     * @param keyword    搜索关键词 支持宝贝ID搜索即keyword=itemid（由于存在特殊符号搜索的关键词必须进行两次urlencode编码）
     * @param shopid     根据店铺id搜索商品 （需要注意的是店铺id搜索暂不支持筛选和排序，如果链接里有关键词和shopid优先搜索店铺id商品）
     * @param back       每页返回条数（请在1,2,10,20,50,100,120,200,500,1000中选择一个数值返回）
     * @param sort       0.综合（最新），1.券后价(低到高)，2.券后价（高到低），3.券面额，4.销量，5.佣金比例，6.券面额（低到高），7.月销量（低到高），8.佣金比例（低到高），9.全天销量（高到低），10全天销量（低到高），11.近2小时销量（高到低），12.近2小时销量（低到高），13.优惠券领取量（高到低），14.好单库指数（高到低）
     * @param cid        0全部，1女装，2男装，3内衣，4美妆，5配饰，6鞋品，7箱包，8儿童，9母婴，10居家，11美食，12数码，13家电，14其他，15车品，16文体
     * @param min_id     分页，用于实现类似分页抓取效果，来源于上次获取后的数据的min_id值，默认开始请求值为1
     * @param price_min  券后价筛选，筛选大于等于所设置的券后价的商品
     * @param price_max  券后价筛选，筛选小于等于所设置的券后价的商品
     * @param sale_min   销量筛选，筛选大于等于所设置的销量的商品
     * @param sale_max   销量筛选，筛选小于等于所设置的销量的商品
     * @param coupon_min 券金额筛选，筛选大于等于所设置的券金额的商品
     * @param coupon_max 券金额筛选，筛选小于等于所设置的券金额的商品
     * @param type       商品筛选类型：type=1是今日上新，type=2是9.9包邮，type=3是30元封顶，type=4是聚划算，type=5是淘抢购，type=6是0点过夜单，type=7是预告单，type=8是品牌单，type=9是天猫商品，type=10是视频单
     * @return
     */
    @Override
    public ServerResponse<ResponeResults> getSearchKeyWord(String keyword, String shopid, Integer back, Integer sort, Integer cid, Integer min_id, Integer price_min,
                                                           Integer price_max, Integer sale_min, Integer sale_max, Integer coupon_min, Integer coupon_max, Integer type, Long userId) {
        // TODO Auto-generated method SearchKeyWord
        Map<String, Object> data = new HashMap<String, Object>();
        if (!StringUtils.isEmpty(keyword)) data.put("keyword", keyword);
        if (!StringUtils.isEmpty(shopid)) data.put("shopid", shopid);
        data.put("back", back == null ? 20 : back);
        data.put("sort", sort == null ? 0 : sort);
        data.put("cid", cid == null ? 0 : cid);
        data.put("min_id", min_id == null ? 1 : min_id);
        if (!StringUtils.isEmpty(price_min)) data.put("price_min", price_min);
        if (!StringUtils.isEmpty(price_max)) data.put("price_max", price_max);
        if (!StringUtils.isEmpty(sale_min)) data.put("sale_min", sale_min);
        if (!StringUtils.isEmpty(sale_max)) data.put("sale_max", sale_max);
        if (!StringUtils.isEmpty(coupon_min)) data.put("coupon_min", coupon_min);
        if (!StringUtils.isEmpty(coupon_max)) data.put("coupon_max", coupon_max);
        if (!StringUtils.isEmpty(type)) data.put("type", type);
        String str = ApiUtils.getData(ApiEnum.GET_KEYWORD_ITEMS, data);
        log.info("获取关键字获取商品信息列表 信息如下：{}", str);
        if (str == null) {
            return ServerResponse.createBySuccessCodeMessage(201, "没有此类商品");
        } else {
            HaoDanKuSearchInfo info = JsonUtils.getJsonToBean(str, HaoDanKuSearchInfo.class);
            if (info != null && info.getCode() == 1 && info.getData().size() > 0) {
                ResponeResults results = taoBaoMethodService.ItemMethon2(info, userId);
                if (results != null) {
                    return ServerResponse.createBySuccess("数据获取成功", results);
                } else {
                    return ServerResponse.createBySuccessCodeMessage(201, "没有此类商品");
                }
            } else {
                return ServerResponse.createBySuccessCodeMessage(201, "没有此类商品");
            }
        }
    }

    /**
     * API
     * 获取超级分类
     */
    @Override
    public ServerResponse<List<GeneralClassify>> getSuperClassify() {

        List<GeneralClassify> classifies = null;

        String redisKeyStr = "app_index_super_classify";

        if (redisTemplateService.hasKey(redisKeyStr)) {
            classifies = redisTemplateService.getTByListKey(redisKeyStr, GeneralClassify.class);
        }
        if (classifies != null && classifies.size() > 0) {
            return ServerResponse.createBySuccess("数据获取成功", classifies);
        }

        String str = ApiUtils.getData(ApiEnum.SUPER_CLASSIFY, "");
        // TODO Auto-generated method SuperClassify
        log.info("获取超级分类信息如下：{}", str);
        if (str == null) {
            return ServerResponse.createBySuccessCodeMessage(201, "没有此类商品");
        } else {
            HaoDanKuSuperClassifyInfo info = JsonUtils.getJsonToBean(str, HaoDanKuSuperClassifyInfo.class);
            if (info != null && info.getCode() == 1 && info.getGeneralClassify() != null) {
                List<GeneralClassify> generalClassifies = info.getGeneralClassify();
                for (GeneralClassify generalClassify : generalClassifies) {
                    if (generalClassify != null && generalClassify.getData() != null) {
                        List<HaoDanKuSuperClassifyInfo.GeneralClassifyData> generalClassifyDatas = generalClassify.getData();
                        if (generalClassifyDatas != null && generalClassifyDatas.size() > 0) {
                            for (HaoDanKuSuperClassifyInfo.GeneralClassifyData generalClassifyData : generalClassifyDatas) {
                                if (generalClassifyData != null && generalClassifyData.getInfo() != null) {
                                    List<HaoDanKuSuperClassifyInfo.GeneralClassifyDataInfo> infos = generalClassifyData.getInfo();
                                    if (infos != null && infos.size() > 0) {
                                        for (HaoDanKuSuperClassifyInfo.GeneralClassifyDataInfo generalClassifyDataInfo : infos) {
                                            if (generalClassifyDataInfo != null && generalClassifyDataInfo.getImgurl() != null) {
                                                generalClassifyDataInfo.setImgurlsmall(generalClassifyDataInfo.getImgurl() == null ? generalClassifyDataInfo.getImgurl() : generalClassifyDataInfo.getImgurl().replace("-600", "-100"));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if (info.getGeneralClassify() != null && info.getGeneralClassify().size() > 0) {
                    redisTemplateService.set(redisKeyStr, info.getGeneralClassify(), 60 * 60);
                }
                return ServerResponse.createBySuccess("数据获取成功", info.getGeneralClassify());
            } else {
                return ServerResponse.createBySuccessCodeMessage(201, "没有此类商品");
            }
        }
    }

    /**
     * API
     * 新---首页二级类目
     */
    @Override
    public ServerResponse getSuperCategory(Integer cid, @RequestParam("0") String appVersion) {
        //appVersion为1 隐藏二级目录
        if ("1".equals(appVersion)) {
            return ServerResponse.createBySuccessCodeMessage(201, "没有此类商品类目");
        }

        List<DaoTaoKeSuperCategoryInfo.GeneralCategoryDataInfo> result = null;

        String redisKeyStr = "app_goods_category2_list_" + cid;
        if (redisTemplateService.hasKey(redisKeyStr)) {
            result = redisTemplateService.getTByListKey(redisKeyStr, DaoTaoKeSuperCategoryInfo.GeneralCategoryDataInfo.class);
        }
        if (result != null && result.size() > 0) {
            return ServerResponse.createBySuccess("数据获取成功", result);
        }

        DaoTaoKeSuperCategoryInfo info = daTaoKeItemInfoService.getSuperCategory();
        log.info("获取超级分类信息如下：{}", info);

        List<List<DaoTaoKeSuperCategoryInfo.GeneralCategoryDataInfo>> list = new ArrayList<>();
        List<DaoTaoKeSuperCategoryInfo.GeneralCategoryDataInfo> listNextName = new ArrayList<>();
        result = new ArrayList<>();
        int sum = 0;
        if (info != null && info.getCode() == 0 && info.getData() != null) {
            List<DaoTaoKeSuperCategoryInfo.GeneralCategory> generalCategory = info.getData();
            for (DaoTaoKeSuperCategoryInfo.GeneralCategory generalClassify : generalCategory) {
                if (generalClassify != null && generalClassify.getSubcategories() != null) {
                    if (cid == 1) {
                        if (generalClassify.getCid() == 1) {
                            list.add(generalClassify.getSubcategories());
                        }
                    } else if (cid == 2) {
                        if (generalClassify.getCid() == 9) {
                            list.add(generalClassify.getSubcategories());
                        }
                    } else if (cid == 3) {
                        if (generalClassify.getCid() == 10 || generalClassify.getCid() == 12) {
                            list.add(generalClassify.getSubcategories());
                        }
                    } else if (cid == 4) {
                        if (generalClassify.getCid() == 3) {
                            list.add(generalClassify.getSubcategories());
                        }
                    } else if (cid == 6) {
                        if (generalClassify.getCid() == 5 || generalClassify.getCid() == 11) {
                            list.add(generalClassify.getSubcategories());
                        }
                    } else if (cid == 9) {
                        if (generalClassify.getCid() == 2) {
                            list.add(generalClassify.getSubcategories());
                        }
                    } else if (cid == 10) {
                        if (generalClassify.getCid() == 4) {
                            list.add(generalClassify.getSubcategories());
                        }
                    } else if (cid == 11) {
                        if (generalClassify.getCid() == 6) {
                            list.add(generalClassify.getSubcategories());
                        }
                    } else if (cid == 12) {
                        if (generalClassify.getCid() == 8) {
                            list.add(generalClassify.getSubcategories());
                        }
                    } else if (cid == 15) {
                        if (generalClassify.getCid() == 7) {
                            list.add(generalClassify.getSubcategories());
                        }
                    } else {
                        return ServerResponse.createBySuccessCodeMessage(201, "没有此类商品类目");
                    }
                }
            }
            if (cid == 4) {//4 美妆
                ServerResponse<List<GeneralClassify>> superClassifyList = getSuperClassify();
                DaoTaoKeSuperCategoryInfo.GeneralCategoryDataInfo generalCategoryDataInfo = null;
                for (GeneralClassify generalClassify : superClassifyList.getData()) {
                    if (4 == generalClassify.getCid()) {
                        for (HaoDanKuSuperClassifyInfo.GeneralClassifyData generalClassifyData : generalClassify.getData()) {
                            int count = 0;
                            for (HaoDanKuSuperClassifyInfo.GeneralClassifyDataInfo generalClassifyDataInfo : generalClassifyData.getInfo()) {
                                if (count == 6) {
                                    continue;
                                }
                                generalCategoryDataInfo = new DaoTaoKeSuperCategoryInfo.GeneralCategoryDataInfo();
                                generalCategoryDataInfo.setScname(generalClassifyDataInfo.getSonName());
                                generalCategoryDataInfo.setSubcname(generalClassifyDataInfo.getSonName());
                                generalCategoryDataInfo.setScpic(generalClassifyDataInfo.getImgurlsmall());
                                listNextName.add(generalCategoryDataInfo);
                                count += 1;
                            }
                        }
                    }
                }

            } else {
                for (List<DaoTaoKeSuperCategoryInfo.GeneralCategoryDataInfo> infoList : list) {
                    for (DaoTaoKeSuperCategoryInfo.GeneralCategoryDataInfo dataInfo : infoList) {
                        dataInfo.setScname(dataInfo.getSubcname());
                        listNextName.add(dataInfo);
                    }
                }
            }
            if (listNextName.size() > 0) {
                Iterator<DaoTaoKeSuperCategoryInfo.GeneralCategoryDataInfo> i = listNextName.iterator();
                while (i.hasNext()) {
                    if (sum < 15) {
                        result.add(i.next());
                    } else {

                        break;
                    }
                    sum += 1;
                }
            }
            if (result != null && result.size() > 0) {
                redisTemplateService.set(redisKeyStr, result, 60 * 60);
            }
            return ServerResponse.createBySuccess("数据获取成功", result);
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "没有此类商品");
        }
    }

    /**
     * API
     * 获取热搜词
     */
    @Override
    public ServerResponse getSearchHotKey() {
        // TODO Auto-generated method getHotKey
        List<KeyWord> words = new ArrayList<KeyWord>();
        String str = null;
        if (redisTemplate.hasKey("HotKeyWords")) {
            str = (String) redisTemplate.opsForValue().get("HotKeyWords");
        } else {
            str = ApiUtils.getData(ApiEnum.HOT_KEY, "");
            redisTemplate.opsForValue().set("HotKeyWords", str, 5, TimeUnit.MINUTES);
        }
        // log.info("获取热搜词信息如下：{}", str);
        if (str == null) {
            return ServerResponse.createBySuccessCodeMessage(201, "暂无热搜");
        } else {
            HaoDanKuHotKeyInfo info = JsonUtils.getJsonToBean(str, HaoDanKuHotKeyInfo.class);

            if (info != null && info.getCode() == 1 && info.getData().size() > 0) {
                if (info.getData().size() > 15) {
                    for (int i = 0; i <= 15; i++) {
                        words.add(info.getData().get(i));
                    }
                } else {
                    for (int i = 0; i <= info.getData().size() - 1; i++) {
                        words.add(info.getData().get(i));
                    }
                }
                words.get(1).setType(1);
                words.get(2).setType(1);
                words.get(6).setType(1);
                words.get(words.size() - 6).setType(1);
                words.get(words.size() - 2).setType(1);
                return ServerResponse.createBySuccess("数据获取成功", words);
            } else {
                return ServerResponse.createBySuccessCodeMessage(201, "暂无热搜");
            }
        }
    }


    /**
     * API
     * 获取热搜词
     */
    @Override
    public ServerResponse getHDKHotKey() {
        // TODO Auto-generated method getHotKey
        List<KeyWord> wordsStart = new ArrayList<KeyWord>();
        List<KeyWord> wordsEnd = new ArrayList<KeyWord>();
        String str = null;
        if (redisTemplate.hasKey("HotKeyWords")) {
            str = (String) redisTemplate.opsForValue().get("HotKeyWords");
        } else {
            str = ApiUtils.getData(ApiEnum.HOT_KEY, "");
            redisTemplate.opsForValue().set("HotKeyWords", str, 5, TimeUnit.MINUTES);
        }
        // log.info("获取热搜词信息如下：{}", str);
        if (str == null) {
            return ServerResponse.createBySuccessCodeMessage(201, "暂无热搜");
        } else {
            HaoDanKuHotKeyInfo info = JsonUtils.getJsonToBean(str, HaoDanKuHotKeyInfo.class);

            HashMap map = new HashMap<>();
            if (info != null && info.getCode() == 1 && info.getData().size() > 0) {
                for (int i = 0; i <= info.getData().size() - 1; i++) {
                    if (info.getData().get(i).getKeyword().length() < 5) {
                        if (wordsStart.size() < 8) {
//                            if (wordsStart.size() < 2) {
//                                info.getData().get(i).setType(1);
//                            } else {
//                                info.getData().get(i).setType(0);
//                            }
                            wordsStart.add(info.getData().get(i));

                        } else {
                            if (wordsEnd.size() < 8) {
//                                if (wordsEnd.size() < 2) {
//                                    info.getData().get(i).setType(1);
//                                } else {
//                                    info.getData().get(i).setType(0);
//                                }
                                wordsEnd.add(info.getData().get(i));
                            }
                        }
                    }
                }
                if (wordsStart.size() > 7) {
                    wordsStart.get(1).setType(1);
                    wordsStart.get(6).setType(1);
                }
                if (wordsEnd.size() > 7) {
                    wordsEnd.get(1).setType(1);
                    wordsEnd.get(6).setType(1);
                }

                map.put("wordsStartList", wordsStart);
                map.put("wordsEndList", wordsEnd);
                return ServerResponse.createBySuccess("数据获取成功", map);
            } else {
                return ServerResponse.createBySuccessCodeMessage(201, "暂无热搜");
            }
        }
    }

    /**
     * API
     * 获取热搜词
     */
    @Override
    public ServerResponse getHDKHotKeyNew() {
        // TODO Auto-generated method getHotKey

        List<KeyWord> wordsStart = new ArrayList<KeyWord>();
        List<KeyWord> wordsEnd = new ArrayList<KeyWord>();
        String str = null;
        if (redisTemplate.hasKey("DTKHotKeyWords")) {
            str = (String) redisTemplate.opsForValue().get("DTKHotKeyWords");
        } else {
            try {
                String url = "http://121.40.189.144:8087/list.json";
                str = DtkHttpUtils.sendGet(url, null);
                if (str.contains("{") || str.contains("[")) {
                    redisTemplate.opsForValue().set("DTKHotKeyWords", str, 1, TimeUnit.HOURS);
                } else {
                    str = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (str == null) {
            return getHDKHotKey();
        } else {
            JSONArray jsonObject = JSONObject.parseArray(str);
            List<Map<String, Object>> keys = JsonUtils.getJsonToListMap(jsonObject.toJSONString());
            if (keys != null || keys.size() > 0) {
                HashMap map = new HashMap<>();
                for (Map keyMap : keys) {
                    for (Object key : keyMap.keySet()) {

                        if (key.equals("name")) {
                            if (wordsStart.size() < 8) {
                                String name = keyMap.get(key).toString();
                                KeyWord keyWord = new KeyWord();
                                keyWord.setKeyword(name);
                                wordsStart.add(keyWord);

                            } else {
                                if (wordsEnd.size() < 8) {
                                    String name = keyMap.get(key).toString();
                                    KeyWord keyWord = new KeyWord();
                                    keyWord.setKeyword(name);
                                    wordsEnd.add(keyWord);
                                }
                            }
                        }
                    }
                }
                if (wordsStart.size() > 7) {
                    wordsStart.get(1).setType(1);
                    wordsStart.get(6).setType(1);
                }
                if (wordsEnd.size() > 7) {
                    wordsEnd.get(1).setType(1);
                    wordsEnd.get(6).setType(1);
                }

                map.put("wordsStartList", wordsStart);
                map.put("wordsEndList", wordsEnd);
                return ServerResponse.createBySuccess("数据获取成功", map);
            } else {
                return ServerResponse.createBySuccessCodeMessage(201, "暂无热搜");
            }
        }

    }

    @Override
    public ServerResponse getSearchKey(String keyword) {
        if (!StringUtils.isEmpty(keyword)) {
            keyword = keyword.replaceAll("\\s*", ""); //可以替换大部分空白字符， 不限于空格 ；
        }
        String a = "https://youngmall-api.youzibuy.com/search/querykey?device_id=865441031838162&bundleid=11&themeid=1&resolution=1080,1920&platform=android&mode=0&myclient=2330297001100000&tbuid=&sdkversion=28&v_auth=7.UVzfDaZm1J_FTgo8uQ-pMdO6TGvmnh8CHVz7ifmX06c&v=2.9.7&imei=865441031838162&myuid=325610161&app_id=23&keyword=" + keyword + "&mall=3&device_id=865441031838162&v=2.9.7&platform=android";
        String sign = MD5Utils.m1(a, "55ce50f066ef7602");
        String url = a + "&sign=" + sign;
        log.info("羊毛省钱请求链接{}" + url);
        String res = DtkHttpUtils.sendGet(url, null);
        JSONObject jsonObject = JSONObject.parseObject(res);
        JSONObject jsonObjectData = jsonObject.getJSONObject("data");
        Integer code = jsonObject.getInteger("code");
        if (code == 200) {
            JSONArray keyWordList = new JSONArray();
            List<KeyWord> wordsStart = new ArrayList<KeyWord>();
            List<KeyWord> wordsEnd = new ArrayList<KeyWord>();
            HashMap map = new HashMap<>();
            JSONArray result = jsonObjectData.getJSONArray("hot_word_group");

            for (int i = 0; i < result.size(); i++) {
                JSONArray WordList = result.getJSONObject(i).getJSONArray("hot_word_list");
                if (WordList.size() == 0) {
                    continue;
                }
                for (int y = 0; y < WordList.size(); y++) {
                    String word = WordList.getJSONObject(y).getString("word");
                    keyWordList.add(word);
                }
            }
            if (keyWordList != null && keyWordList.size() > 0) {
                for (Object listword : keyWordList) {
                    if (wordsStart.size() < 6) {
                        KeyWord keyWord = new KeyWord();
                        keyWord.setKeyword(listword.toString());
                        wordsStart.add(keyWord);

                    } else {
                        if (wordsEnd.size() < 6) {
                            KeyWord keyWord = new KeyWord();
                            keyWord.setKeyword(listword.toString());
                            wordsEnd.add(keyWord);
                        }
                    }
                }
                if (wordsEnd.size() < 6) {
                    wordsEnd.clear();
                    map.put("wordsEndList", wordsEnd);
                } else {
                    map.put("wordsEndList", wordsEnd);
                }
                if (wordsStart.size() < 6) {
                    wordsStart.clear();
                    map.put("wordsStartList", wordsStart);
                } else {
                    map.put("wordsStartList", wordsStart);
                }
//                map.put("wordsStartList", wordsStart);
//                map.put("wordsEndList", wordsEnd);
                return ServerResponse.createBySuccess("数据获取成功", map);
            } else {
                return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
            }

        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
        }
    }

    /**
     * 淘宝API
     * 猜你喜欢
     *
     * @param itemId        获取猜你喜欢的类型商品的宝贝ID
     * @param pageSize      页大小，默认20，1~100
     * @param pageNo        第几页，默认：1
     * @param deviceValue   设备号
     * @param deviceEncrypt 设备号加密类型：MD5
     * @param deviceType    设备号类型：IMEI，或者IDFA，或者UTDID
     * @return https://open.taobao.com/api.htm?docId=33947&docType=2&scopeId=11655
     */
    @Override
    public List<TbkDgOptimusMaterialResponse.MapData>
    getSimilarInfo2(Long itemId, String deviceValue, String deviceEncrypt, String deviceType,
                    Long pageSize, Long pageNo) {
        // TODO Auto-generated method getSimilarInfo2
        TaobaoClient client = new DefaultTaobaoClient(ApiEnum.TAO_URL, ApiEnum.TAO_APPKEY, ApiEnum.TAO_SECRET);
        TbkDgOptimusMaterialRequest req = new TbkDgOptimusMaterialRequest();
        req.setPageSize(pageSize == null ? 20 : pageSize);
        req.setAdzoneId(ApiEnum.TAO_ADZONEID);
        req.setPageNo(pageNo == null ? 1 : pageNo);
        req.setMaterialId(6708L);
        if ("UTDID".equals(deviceType)) {
            req.setDeviceValue(deviceValue);
        } else {
            req.setDeviceValue(MD5Utils.createMD5(deviceValue));
        }
        req.setDeviceEncrypt(deviceEncrypt);
        req.setDeviceType(deviceType);
        req.setItemId(itemId);
        TbkDgOptimusMaterialResponse rsp;
        try {
            rsp = client.execute(req);
            log.info("获取到猜你喜欢数据：{}", rsp.getBody());
            log.info("请求的参数：{}", rsp.getParams());
            log.info("请求的url：{}", rsp.getRequestUrl());
            if (rsp.isSuccess()) {
                return rsp.getResultList();
            } else {
                return null;
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取首页类目
     */
    @Override
    // @Cacheable("getClassify")
    public ServerResponse<List<AppGoodsClassify>> getClassify() {

        String redisKeyStr = "app_goods_category_list";
        List<AppGoodsClassify> classifies = null;
        if (redisTemplateService.hasKey(redisKeyStr)) {
            classifies = redisTemplateService.getTByListKey(redisKeyStr, AppGoodsClassify.class);
        }
        if (classifies == null) {
            classifies = iAppGoodsClassifyService.selectAppGoodsClassifyList(null);
            if (classifies != null || classifies.size() > 0) {
                redisTemplateService.set(redisKeyStr, classifies, 0);
            }
        }
        if (classifies != null || classifies.size() > 0) {
            log.info("获取到首页类目数据{}", classifies.size());
            return ServerResponse.createBySuccess("数据获取成功", classifies);
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "没有此类商品");
        }
    }


    /**
     * API
     * 根据商品ID获取商品详情
     *
     * @param ItemId
     * @return
     */
    @Override
    public ServerResponse<ResponeResults> getHdkSearchItemIdDetail(String ItemId, Long userId, String
            channelUserId, String period, Integer isCollect, String activityId) {
        // TODO Auto-generated method getHdkSearchItemIdDetail
        if (!StringUtils.isEmpty(ItemId)) {
            AppGoods appGoods = iAppGoodsService.findAppGoodsByItemId(ItemId);

            if (appGoods != null) {
                if (StringUtils.isEmpty(appGoods.getActivityid())) {
                    appGoods.setActivityid(activityId);
                }
                log.info("{}获取到本地商品详情{}", ItemId, appGoods.getItemid());
                ResponeResults results = taoBaoMethodService.ItemMethon7(appGoods, userId, channelUserId, period, isCollect);
                if (results != null) {
                    return ServerResponse.createBySuccess("数据获取成功", results);
                } else {
                    if (results.getMin_id() == 601) {
                        return ServerResponse.createBySuccessCodeMessage(601, "商品已下架");
                    }
                    return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
                }
            }
            //从大淘客获取
            DTKResponse dtkResponse = daTaoKeItemInfoService.itemInfoByItemId(ItemId);
            if (dtkResponse != null && dtkResponse.getCode() == 0 && dtkResponse.getData() != null) {//code为0 成功
                log.info("{}获取到大淘客商品详情{}", ItemId, dtkResponse.getData());
                AppGoods goods = HDKUtils.getAppGoodsFromDTK(dtkResponse.getData());
                if (StringUtils.isEmpty(goods.getActivityid())) {
                    goods.setActivityid(activityId);
                }
                ResponeResults results = taoBaoMethodService.ItemMethon7(goods, userId, channelUserId, period, isCollect);

                if (goods != null) {
                    return ServerResponse.createBySuccess("数据获取成功", results);
                } else {
                    if (results.getMin_id() == 601) {
                        return ServerResponse.createBySuccessCodeMessage(601, "商品已下架");
                    }
                    return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
                }
            } else {
                //从好单库获取
                String str = ApiUtils.getData(ApiEnum.ITEM_DETAIL, "itemid/" + ItemId + "/");
                HaoDanKuItemInfo info = JsonUtils.getJsonToBean(str, HaoDanKuItemInfo.class);
                if (info != null && info.getCode() == 1 && info.getData() != null) {//code为1 成功
                    log.info("{}获取到好单库商品详情{}", ItemId, str);
                    ResponeResults results = taoBaoMethodService.ItemMethon3(info, userId, channelUserId, period, isCollect);
                    if (results != null) {
                        return ServerResponse.createBySuccess("数据获取成功", results);
                    } else {
                        if (results.getMin_id() == 601) {
                            return ServerResponse.createBySuccessCodeMessage(601, "商品已下架");
                        }
                        return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
                    }
                } else {
                    ServerResponse<List<NTbkItem>> response = getSearchItemIdDetail(ItemId);
                    if (response.getStatus() == 200) {
                        log.info("{}获取到淘宝商品详情{}", ItemId, response.getData().size());
                        ResponeResults results = taoBaoMethodService.ItemMethon6(response.getData(), userId, channelUserId, isCollect);
                        if (results != null) {
                            return ServerResponse.createBySuccess("数据获取成功", results);
                        } else {
                            if (results.getMin_id() == 601) {
                                return ServerResponse.createBySuccessCodeMessage(601, "商品已下架");
                            }
                            return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
                        }
                    } else {
                        return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
                    }
                }
            }
        } else {
            return ServerResponse.createByErrorMessage("参数无效-未传入[商品ID]");
        }
    }

    /**
     * Eco API
     * 根据商品ID获取商品详情
     *
     * @param ItemId http://taobaoapi.ecostudio.cn/taobao/itemId/itemdetail?itemId=556384325501
     * @return
     */
    @Override
    public ServerResponse<List<NTbkItem>> getSearchItemIdDetail(String ItemId) {
        // TODO Auto-generated method SearchItemId
        if (!StringUtils.isEmpty(ItemId)) {
//            String str = ApiUtils.getEcoData(ApiEnum.TAOBAO_ITEMID_ITEMDETAIL, "itemId=" + ItemId);

            String redisKeyStr = "app_goods_itemIdDetail_" + ItemId;

            List<NTbkItem> nTbkItems = new ArrayList<>();
            if (redisTemplateService.hasKey(redisKeyStr) && ItemId.length() < 20) {
                nTbkItems = redisTemplateService.getTByListKey(redisKeyStr, NTbkItem.class);
            }
            if (nTbkItems == null || nTbkItems.size() <= 0) {

                String str = null;
                TbkItemInfoGetResponse tbkItemInfoGetResponse = itemInfoController.itemInfoByItemId(ItemId);
                log.info("第一次调用itemInfoByItemId{}——", ItemId);
                if ("50001".equals(tbkItemInfoGetResponse.getSubCode())) {
                    tbkItemInfoGetResponse = itemInfoController.itemInfoByItemId(ItemId);
                    log.info("50001第二次调用itemInfoByItemId--", ItemId);
                }
                if (tbkItemInfoGetResponse != null) {
                    str = JSON.toJSONString(tbkItemInfoGetResponse);
                }
                log.debug("获取Eco商品详情信息如下：{}", str);
                if (str != null && !"".equals(str)) {
                    TbkItemInfoGetInfo info = JsonUtils.getJsonToBean(str, TbkItemInfoGetInfo.class);
                    if (info != null && info.isSuccess()) {
                        nTbkItems = info.getResults();
                    }
                }
                redisTemplateService.set(redisKeyStr, nTbkItems, 60 * 5);
            }
            if (nTbkItems != null && nTbkItems.size() > 0) {
                return ServerResponse.createBySuccess("数据获取成功", nTbkItems);
            } else {
                return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
            }
        } else {
            return ServerResponse.createByErrorMessage("参数无效-未传入商品ID");
        }
    }

    /**
     * Eco API
     * 根据商品ID进行高佣转链
     *
     * @param itemId 商品ID
     * @param userId 站点ID
     * @return
     */
    @Override
    public ServerResponse<TbkPrivilege> getPrivilegeItemId(Long itemId, Long userId, Integer jumpType) {
        // TODO Auto-generated method getPrivilegeItemId
        StringBuilder builder = new StringBuilder();

        if (null != userId && 0 != userId) {
            //根据用户id，查询所属公司，用户不存在查询总公司
            AppUser user = iAppUserService.selectAppUserByUserId(userId, 0);
            AppCompany com;
            TaobaoScheme taobaoScheme = null;
            String generalizePid = "";
            String appSession = "";

            //用户不为空，推广id不为空时，查询用户对应的推广位
            if (user != null && user.getSchemeId() != null && user.getSchemeId() != 0) {
                taobaoScheme = iTaobaoSchemeService.selectTaobaoSchemeById(user.getSchemeId(), 0);
                if (taobaoScheme != null && taobaoScheme.getGeneralizePid() != null && taobaoScheme.getAppSession() != null) {
                    generalizePid = taobaoScheme.getGeneralizePid();
                    appSession = taobaoScheme.getAppSession();
                }
            }
            //generalizePid或者appSession 为空时，取公司的值
            boolean isNotHasScheam = (StringUtils.isEmpty(generalizePid) || StringUtils.isEmpty(appSession));

            if (isNotHasScheam) {
                com = appCompanyService.findtAppCompany(user == null ? null : user.getCompanyId(), 1);
                generalizePid = com.getGeneralizePid();
                appSession = com.getTaoBaoScheme().getAppSession();
            }
            builder.append(itemId);
            builder.append("/").append(generalizePid.split("_")[2]);
            builder.append("/").append(generalizePid.split("_")[3]);
            builder.append("/").append(appSession);
//            String str = ApiUtils.getEcoData(ApiEnum.PRIVILEGE_ITEMID_SITELD_ADZONEID_SESSION, builder.toString());
            String str = "";
            // TbkPrivilegeGetResponse tbkPrivilegeGetResponse = sessionController.tbkPrivilegeGetResponse(itemId, Long.parseLong(com.getGeneralizePid().split("_")[2]), Long.parseLong(com.getGeneralizePid().split("_")[3]), com.getTaoBaoScheme().getAppSession());
//            String redisKeyStr = "app_goods_privilege_" + itemId + "_" + generalizePid + "_" + appSession;
            TbkPrivilegeGetInfo info = null;
//            if (redisTemplateService.hasKey(redisKeyStr)) {
//                JSONObject jsonObject = redisTemplateService.getTByKey(redisKeyStr, JSONObject.class);
//                str = jsonObject == null ? null : jsonObject.toJSONString();
//            }
            str = null;
            if (str == null || "".equals(str)) {
                TbkPrivilegeGetResponse tbkPrivilegeGetResponse = sessionController.tbkPrivilegeGetResponse(itemId, Long.parseLong(generalizePid.split("_")[2]), Long.parseLong(generalizePid.split("_")[3]), appSession);
                log.info("第一次调用tbkPrivilegeGetResponse{}==", itemId);
                if ("50001".equals(tbkPrivilegeGetResponse.getSubCode())) {
                    log.info("50001第二次调用tbkPrivilegeGetResponse==", itemId);
                    tbkPrivilegeGetResponse = sessionController.tbkPrivilegeGetResponse(itemId, Long.parseLong(generalizePid.split("_")[2]), Long.parseLong(generalizePid.split("_")[3]), appSession);
                }

                if (tbkPrivilegeGetResponse != null) {
                    str = JSON.toJSONString(tbkPrivilegeGetResponse);
                    if (str == null || "".equals(str)) {

                        return ServerResponse.createByErrorCodeMessage(601, "商品不存在");
                    }
                    info = JsonUtils.getJsonToBean(str, TbkPrivilegeGetInfo.class);
//                    if (info != null && info.isSuccess()) {
//                        redisTemplateService.set(redisKeyStr, JSON.parseObject(str), 60 * 5);
//                    }
                }
                log.info("用户UserId:{},获取高佣转链信息{}", userId, str);
            } else {
                info = JsonUtils.getJsonToBean(str, TbkPrivilegeGetInfo.class);
            }

            if (info != null && info.isSuccess()) {
                String coupon = RegUtils.getreGex(info.getResult().getData().getCouponInfo() == null ? "减0元" : info.getResult().getData().getCouponInfo(), "(?<=减)[0-9]*(?=元)");
                TbkPrivilegeGetInfo.TbkPrivilege tbkPrivilege = info.getResult().getData();
                if ((user.getRelationId() == null || user.getRelationId() == 0) && (user.getSpecialId() != null && user.getSpecialId() != 0)) {
                    tbkPrivilege.setItemUrl(tbkPrivilege.getItemUrl() + "&specialId=" + user.getSpecialId());//relationId
                    tbkPrivilege.setCouponClickUrl(tbkPrivilege.getCouponClickUrl() + "&specialId=" + user.getSpecialId());
                } else {
                    tbkPrivilege.setItemUrl(tbkPrivilege.getItemUrl() + "&relationId=" + user.getRelationId());//relationId
                    tbkPrivilege.setCouponClickUrl(tbkPrivilege.getCouponClickUrl() + "&relationId=" + user.getRelationId());
                }
                if (null == coupon || "0".equals(coupon)) {
                    info.getResult().getData().setCouponInfo(null);
                } else {
                    info.getResult().getData().setCouponInfo(coupon);
                }
                //商品Id+userId+type存redis
                if (jumpType != null) {
                    HashMap<Object, Object> map = new HashMap<>();
                    map.put("itemId", itemId);
                    map.put("jumpType", jumpType);
                    List<Map<Object, Object>> map1 = (List<Map<Object, Object>>) redisTemplate.opsForList().range("app_buy_source_" + userId, 0, -1);
                    if (map1.size() > 0) {
                        List<String> orderSourceList = new ArrayList<>();
                        for (Map orderSource : map1) {
                            if (orderSource.get("itemId").equals(itemId)) {
                                orderSourceList.add(orderSource.get("jumpType").toString());
                            }
                        }
                        if (!orderSourceList.contains(jumpType.toString())) {
                            redisTemplate.opsForList().rightPush("app_buy_source_" + userId, map);
                        }
                    } else {
                        redisTemplate.opsForList().rightPush("app_buy_source_" + userId, map);
                        redisTemplate.expire("app_buy_source_" + userId, 24, TimeUnit.HOURS);
                    }
                }
                log.info("转链结果{}{}{}", userId, tbkPrivilege.getItemUrl(), tbkPrivilege.getCouponClickUrl());
                return ServerResponse.createBySuccess("数据获取成功", tbkPrivilege);
            } else {
                if (info.getSubCode().contains("isv.item-not-exist")) {
                    return ServerResponse.createByErrorCodeMessage(601, "商品失效");
                }
                return ServerResponse.createByErrorCodeMessage(601, "商品不存在");
            }
        } else {
            AppCompany com = appCompanyService.findtAppCompany(null, 1);

            String generalizePid = com.getGeneralizePid();
            String appSession = com.getTaoBaoScheme().getAppSession();

            builder.append(itemId);
            builder.append("/").append(generalizePid.split("_")[2]);
            builder.append("/").append(generalizePid.split("_")[3]);
            builder.append("/").append(appSession);
//            String str = ApiUtils.getEcoData(ApiEnum.PRIVILEGE_ITEMID_SITELD_ADZONEID_SESSION, builder.toString());

            String redisKeyStr = "app_goods_privilege_" + itemId + "_" + generalizePid + "_" + appSession;
            TbkPrivilegeGetInfo info = null;
            String str = "";
            if (redisTemplateService.hasKey(redisKeyStr)) {
                JSONObject jsonObject = redisTemplateService.getTByKey(redisKeyStr, JSONObject.class);
                str = jsonObject == null ? null : jsonObject.toJSONString();
            }
            if (str == null || "".equals(str)) {
                TbkPrivilegeGetResponse tbkPrivilegeGetResponse = sessionController.tbkPrivilegeGetResponse(itemId, Long.parseLong(generalizePid.split("_")[2]), Long.parseLong(generalizePid.split("_")[3]), appSession);
                log.info("第一次调用tbkPrivilegeGetResponse");
                if ("50001".equals(tbkPrivilegeGetResponse.getSubCode())) {
                    log.info("50001第二次调用tbkPrivilegeGetResponse");
                    tbkPrivilegeGetResponse = sessionController.tbkPrivilegeGetResponse(itemId, Long.parseLong(generalizePid.split("_")[2]), Long.parseLong(generalizePid.split("_")[3]), appSession);
                }

                if (tbkPrivilegeGetResponse != null) {
                    str = JSON.toJSONString(tbkPrivilegeGetResponse);
                    if (str == null || "".equals(str)) {

                        return ServerResponse.createByErrorCodeMessage(601, "商品不存在");
                    }
                    info = JsonUtils.getJsonToBean(str, TbkPrivilegeGetInfo.class);
                    if (info != null && info.isSuccess()) {
                        redisTemplateService.set(redisKeyStr, JSON.parseObject(str), 60 * 5);
                    }
                }
                log.info("无用户ID获取高佣转链信息{}", str);
            } else {
                info = JsonUtils.getJsonToBean(str, TbkPrivilegeGetInfo.class);
            }

            if (info != null && info.isSuccess()) {
                String coupon = RegUtils.getreGex(info.getResult().getData().getCouponInfo() == null ? "减0元" : info.getResult().getData().getCouponInfo(), "(?<=减)[0-9]*(?=元)");
                if (null == coupon || "0".equals(coupon)) {
//                        info.getResult().getData().setItemUrl(info.getResult().getData().getItemUrl());
                    info.getResult().getData().setCouponInfo(null);
                    return ServerResponse.createBySuccess("数据获取成功", info.getResult().getData());
                } else {
//                        info.getResult().getData().setCouponClickUrl(info.getResult().getData().getCouponClickUrl());
                    info.getResult().getData().setCouponInfo(coupon);
                    return ServerResponse.createBySuccess("数据获取成功", info.getResult().getData());
                }
            } else {
                if (info.getSubCode().contains("isv.item-not-exist")) {
                    return ServerResponse.createByErrorCodeMessage(601, "商品失效");
                }
                return ServerResponse.createByErrorCodeMessage(601, "商品不存在");
            }
        }
    }

    /**
     * Eco API
     * 解析淘口令
     *
     * @param tkl 淘口令
     * @return
     */
    @SuppressWarnings("deprecation")
    @Override
    public ServerResponse<TbkItemConvertData> TaobaoAnalyzeTklNew(String tkl, AppCompany appCompany, TaobaoScheme
            taobaoScheme) {

//        String[] specialCharacters = {"《", "￥", "£", "$", "€", "₤", "¢", "₴", "₰", "(", ")", "₳"};
//        for (String specialCharacter : specialCharacters) {
//            tkl = tkl.replaceAll(specialCharacter, "￥");
//        }

        // TODO Auto-generated method TaobaoAnalyzeTkl
        String str = null;
        if (!StringUtils.isEmpty(tkl)) {
            Long adzoneId = null;
            Long siteId = null;
            try {
                adzoneId = (taobaoScheme == null || taobaoScheme.getGeneralizePid() == null) ? null : Long.parseLong(taobaoScheme.getGeneralizePid().split("_")[3]);
                siteId = (taobaoScheme == null || taobaoScheme.getGeneralizePid() == null) ? null : Long.parseLong(taobaoScheme.getGeneralizePid().split("_")[2]);

                String sessionKey = (taobaoScheme == null) ? null : taobaoScheme.getAppSession();
//                TbkTpwdConvertResponse response = tklController.tklGet(tkl, adzoneId);
                TbkScTpwdConvertResponse response = tklController.tklGet2(tkl, adzoneId, siteId, sessionKey);
                log.info("第一次调用tklGet2");
                if (response == null) {
                    log.info("50001第二次调用tklGet2");
                    response = tklController.tklGet2(tkl, adzoneId, siteId, sessionKey);
                }
                str = JSON.toJSONString(response);
            } catch (Exception e) {

            }

            log.info("获取淘口令信息如下：{}", str);
            if (str == null) {
                return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
            } else {
                TbkItemConvertInfo info = JsonUtils.getJsonToBean(str, TbkItemConvertInfo.class);
                if (info != null && info.isSuccess()) {
                    return ServerResponse.createBySuccess("数据获取成功", info.getData());
                } else {
                    return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
                }
            }
        } else {
            return ServerResponse.createByErrorMessage("参数无效-未传入淘口令");
        }
    }

    /**
     * Eco API
     * 解析淘口令
     *
     * @param tkl 淘口令
     * @return
     */
    @SuppressWarnings("deprecation")
    @Override
    public ServerResponse<TbkItemConvertData> TaobaoAnalyzeTkl(String tkl) {

//        String[] specialCharacters = {"《", "￥", "£", "$", "€", "₤", "¢", "₴", "₰", "(", ")", "₳"};
//        for (String specialCharacter : specialCharacters) {
//            tkl = tkl.replaceAll(specialCharacter, "￥");
//        }

        // TODO Auto-generated method TaobaoAnalyzeTkl
        if (!StringUtils.isEmpty(tkl)) {
            String str = ApiUtils.getEcoDataO(ApiEnum.TAOBAO_ANALYZETKL, "tkl=" + URLEncoder.encode(tkl));
            log.info("获取淘口令信息如下：{}", str);
            if (str == null) {
                return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
            } else {
                TbkItemConvertInfo info = JsonUtils.getJsonToBean(str, TbkItemConvertInfo.class);
                if (info != null && info.isSuccess()) {
                    return ServerResponse.createBySuccess("数据获取成功", info.getData());
                } else {
                    return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
                }
            }
        } else {
            return ServerResponse.createByErrorMessage("参数无效-未传入淘口令");
        }
    }

    /**
     * Eco API
     * 生成淘口令
     *
     * @param itemTitle 弹窗的标题
     * @param couponUrl 弹窗的商品链接 无优惠券时传s.click.taobao.com开头的链接
     * @return
     */
    @SuppressWarnings("deprecation")
    @Override
    public ServerResponse<String> TaobaoCreateTkl(String itemTitle, String ItemPic, String couponUrl,
                                                  Long userId) {
        // TODO Auto-generated method TaobaoCreateTkl
        StringBuilder builder = new StringBuilder();
        if (null != userId && 0 != userId) {
            AppUser user = iAppUserService.selectAppUserByUserId(userId);
            if (user != null && user.getRelationId() != null && !"0".equals(user.getRelationId().toString())) {
                if (itemTitle != null && ItemPic != null && couponUrl != null) {
//                    builder.append("itemTitle=").append(URLEncoder.encode(itemTitle));
//                    builder.append("&ItemPic=").append(URLEncoder.encode(ItemPic));
//                    if (RegUtils.getreGex(couponUrl, "relationId") != null) {
//                        builder.append("&couponUrl=").append(URLEncoder.encode(couponUrl));
//                    } else {
//                        builder.append("&couponUrl=").append(URLEncoder.encode(couponUrl) + "&relationId=" + user.getRelationId());
//                    }
//                    String str = ApiUtils.postEcoData(ApiEnum.TAOBAO_CREATETKL, builder.toString());

                    String str = null;
                    Object object = null;
                    if (RegUtils.getreGex(couponUrl, "relationId") != null) {
                        object = tklController.tklPost(itemTitle, ItemPic, couponUrl);
                    } else {
                        couponUrl = couponUrl + "&relationId=" + user.getRelationId();
                        object = tklController.tklPost(itemTitle, ItemPic, couponUrl);
                    }
                    if (object != null) {
                        str = JSON.toJSONString(object);
                        if (str == null) {
                            return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
                        } else {
                            log.info("获取生成淘口令信息如下：{}", str);
                            TbkTpwdCreateInfo info = JsonUtils.getJsonToBean(str, TbkTpwdCreateInfo.class);
                            if (info != null && info.isSuccess()) {
                                log.info("生成的淘口令如下：{}", info.getData().getModel());
                                return ServerResponse.createBySuccess("数据获取成功", info.getData().getModel());
                            } else {
                                return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
                            }
                        }
                    } else {
                        return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
                    }
                }
            }
        }
        return ServerResponse.createByErrorMessage("参数无效");
    }

    /**
     * Eco API
     * 生成淘口令
     */
    @Override
    public ServerResponse<String> TaobaoCreateTklNew(String itemId, String itemTitle, String itemPic, String
            shareUrl, Long userId) {
        // TODO Auto-generated method TaobaoCreateTkl
        if (null != userId && 0 != userId) {
            AppUser user = iAppUserService.selectAppUserByUserId(userId);
            if (user != null) {
                String couponUrl = null;
                ServerResponse<TbkPrivilege> response = getPrivilegeItemId(NumberUtils.toLong(itemId), userId, null);
                if (response != null && response.getData() != null) {
                    couponUrl = response.getData().getCouponClickUrl();
                }
                String str = null;
                Object object = null;
                if (RegUtils.getreGex(couponUrl, "relationId") != null || RegUtils.getreGex(couponUrl, "specialId") != null) {
                    object = tklController.tklPost(itemTitle, itemPic, couponUrl);
                } else {
                    couponUrl = couponUrl + "&relationId=" + user.getRelationId();
                    object = tklController.tklPost(itemTitle, itemPic, couponUrl);
                }
                if (object != null) {
                    str = JSON.toJSONString(object);
                    if (str == null) {
                        return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
                    } else {
                        log.info("获取生成淘口令信息如下：{}", str);
                        TbkTpwdCreateInfo info = JsonUtils.getJsonToBean(str, TbkTpwdCreateInfo.class);
                        if (info != null && info.isSuccess()) {
                            log.info("生成的淘口令如下：{}", info.getData().getModel());

                            String tklStr = "【" + itemTitle + "】" + shareUrl + "  点击链接，再选择浏览器打开；或复制这条信息，打开\uD83D\uDC49手淘\uD83D\uDC48" + info.getData().getModel();
                            return ServerResponse.createBySuccess("数据获取成功", tklStr);
                        } else {
                            return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
                        }
                    }
                } else {
                    return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
                }
            }
        }
        return ServerResponse.createByErrorMessage("参数无效");
    }

    //渠道授权
//	@Override
//	public ServerResponse<Data> getRelationId(String inviterCode, long infoType, String note,
//			String sessionKey,Long taobaoId) {
//		// TODO Auto-generated method getRelationId
//		log.info("message用户备案信息note字段{}.{}",note,taobaoId);
//		TaobaoClient client = new DefaultTaobaoClient(ApiEnum.TAO_URL, ApiEnum.TAO_APPKEY, ApiEnum.TAO_SECRET);
//		TbkScPublisherInfoSaveRequest req = new TbkScPublisherInfoSaveRequest();
//		req.setOnlineScene("3");
//		req.setInviterCode(inviterCode);
//		req.setInfoType(infoType);
//		req.setNote(note+"."+taobaoId);
//		TbkScPublisherInfoSaveResponse rsp;
//		try {
//			rsp = client.execute(req, sessionKey);
//			if(rsp.isSuccess()) {
//				log.info("message获取用户{}渠道ID为：{}",taobaoId,rsp.getData().getRelationId());
//				return ServerResponse.createBySuccess(rsp.getData().getDesc(),rsp.getData());
//			}else {
//				return ServerResponse.createByErrorMessage(rsp.getSubMsg());
//			}
//		} catch (ApiException e) {
//			e.printStackTrace();
//		}
//		return ServerResponse.createByErrorMessage("获取授权失败");
//	}

    /**
     * 渠道授权
     * Eco 淘宝API
     * 使用渠道备案api获取渠道ID
     * https://open.taobao.com/api.htm?docId=37988&docType=2&scopeId=14474
     *
     * @param inviterCode
     * @param sessionKey
     * @param note
     * @param userId
     * @return
     */
    @Override
    public ServerResponse<Data> getRelationId2(String inviterCode, String sessionKey, String note, Long userId) {
        // TODO Auto-generated method getRelationId2
        log.info("渠道备案授权-邀请码{}session值{}用户备案备注{}用户ID{}", inviterCode, sessionKey, note, userId);
        StringBuilder builder = new StringBuilder();
        builder.append("inviterCode=").append(inviterCode);
        builder.append("&session=").append(sessionKey);
        builder.append("&note=").append(note + "." + userId);
//        String str = ApiUtils.postEcoData(ApiEnum.TAOBAO_TBK_SCPUBLISHERINFO, builder.toString());
        String str = "";
        TbkScPublisherInfoSaveResponse tbkScPublisherInfoSaveResponse = searchController.tbkScPublisherInfo(inviterCode, sessionKey, note + "." + userId);
        if (tbkScPublisherInfoSaveResponse != null) {
            str = JSON.toJSONString(tbkScPublisherInfoSaveResponse);
        }

        TbkScPublisherInfoSaveResponse response = JsonUtils.getJsonToBean(str, TbkScPublisherInfoSaveResponse.class);
        if (response.isSuccess()) {
            log.info("渠道备案授权-返回数据{}用户渠道ID为：{}", response.getBody(), response.getData().getRelationId());
            return ServerResponse.createBySuccess(response.getData().getDesc(), response.getData());
        } else {
            return ServerResponse.createByErrorMessage(response.getSubMsg());
        }
    }

    /**
     * 会员授权
     * Eco 淘宝API
     * 使用会员备案api获取会员ID
     * https://open.taobao.com/api.htm?docId=37988&docType=2&scopeId=14474
     *
     * @param inviterCode
     * @param sessionKey
     * @param note
     * @param userId
     * @return
     */
    @Override
    public ServerResponse<Data> getSpecialId2(String inviterCode, String sessionKey, String note, Long userId) {
        // TODO Auto-generated method getRelationId2
        log.info("会员备案授权-邀请码{}session值{}用户备案备注{}用户ID{}", inviterCode, sessionKey, note, userId);
        StringBuilder builder = new StringBuilder();
        builder.append("inviterCode=").append(inviterCode);
        builder.append("&session=").append(sessionKey);
        builder.append("&note=").append(note + "." + userId);
//        String str = ApiUtils.postEcoData(ApiEnum.TAOBAO_TBK_SCPUBLISHERINFO, builder.toString());
        String str = "";
        TbkScPublisherInfoSaveResponse tbkScPublisherInfoSaveResponse = searchController.tbkScPublisherInfo(inviterCode, sessionKey, note + "." + userId);
        if (tbkScPublisherInfoSaveResponse != null) {
            str = JSON.toJSONString(tbkScPublisherInfoSaveResponse);
        }
        TbkScPublisherInfoSaveResponse response = JsonUtils.getJsonToBean(str, TbkScPublisherInfoSaveResponse.class);
        if (response.isSuccess()) {
            log.info("会员备案授权-返回数据{}用户渠道ID为：{}", response.getBody(), response.getData().getSpecialId());
            return ServerResponse.createBySuccess(response.getData().getDesc(), response.getData());
        } else {
            return ServerResponse.createByErrorMessage(response.getSubMsg());
        }
    }
    //渠道授权
//	@Override
//	public ServerResponse<Data> getRelationId2(
//			String inviterCode, String sessionKey, String note, Long userId) {
//		// TODO Auto-generated method getRelationId
//		log.info("message用户备案信息note字段{}.{}",note,userId);
//		TaobaoClient client = new DefaultTaobaoClient(ApiEnum.TAO_URL, ApiEnum.TAO_APPKEY, ApiEnum.TAO_SECRET);
//		TbkScPublisherInfoSaveRequest req = new TbkScPublisherInfoSaveRequest();
//		req.setOnlineScene("3");
//		req.setInviterCode(inviterCode);
//		req.setInfoType(1L);
//		req.setNote(note+"."+userId);
//		TbkScPublisherInfoSaveResponse rsp;
//		try {
//			rsp = client.execute(req, sessionKey);
//			if(rsp.isSuccess()) {
//				log.info("message获取用户{}渠道ID为：{}",userId,rsp.getData().getRelationId());
//				return ServerResponse.createBySuccess(rsp.getData().getDesc(),rsp.getData());
//			}else {
//				return ServerResponse.createByErrorMessage(rsp.getSubMsg());
//			}
//		} catch (ApiException e) {
//			e.printStackTrace();
//		}
//		return ServerResponse.createByErrorMessage("获取授权失败");
//	}

    //渠道信息查询
//	@Override
//	public ServerResponse<com.taobao.api.response.TbkScPublisherInfoGetResponse.Data> getTaobaoTbkScPublisherInfoGet(String sessionKey,Long infoType, Long relationId, Long specialId,
//			String relationApp, Long pageNo, Long pageSize) {
//		// TODO Auto-generated method getTaobaoTbkScPublisherInfoGet
//		TaobaoClient client = new DefaultTaobaoClient(ApiEnum.TAO_URL, ApiEnum.TAO_APPKEY, ApiEnum.TAO_SECRET);
//		TbkScPublisherInfoGetRequest req = new TbkScPublisherInfoGetRequest();
//		req.setInfoType(infoType == null?1:infoType);
//		req.setRelationId(relationId);//渠道ID
//		req.setPageNo(pageNo == null?1:pageNo);
//		req.setPageSize(pageSize == null?100:pageSize);
//		req.setRelationApp(relationApp == null?"common":relationApp);
//		//req.setSpecialId("1212");//会员ID
//		TbkScPublisherInfoGetResponse rsp;
//		try {
//			rsp = client.execute(req, sessionKey);
//			if(rsp.isSuccess()) {
//				log.info("message渠道信息查询{}",rsp.getBody());
//				return ServerResponse.createBySuccess("数据获取成功",rsp.getData());
//			}else {
//				return ServerResponse.createByErrorMessage(rsp.getSubMsg());
//			}
//
//		} catch (ApiException e) {
//			e.printStackTrace();
//		}
//		return ServerResponse.createByErrorMessage("获取授权信息查询失败");
//	}

    /**
     * 首页弹窗方法
     *
     * @param str  内容
     * @param type 类型1标题查询2淘口令查询3商品ID查询
     * @return
     */
    @Override
    public ServerResponse<ResponeResults> Popup(String str, Integer type, Long userId) {
        log.info(str);
        // TODO Auto-generated method Popup
        if (!"".equals(str) && str != null && type != null) {
            if (type == 3) {
                if (str.contains("&")) {
                    str = str.substring(0, str.indexOf("&"));
                }
                if (RegUtils.isNumeric(str)) {
                    ResponeResults results = taoBaoMethodService.ItemMethon(str, userId, null);
                    if (results != null) {
                        return ServerResponse.createBySuccess("数据获取成功", results);
                    } else {
                        return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
                    }
                } else {
                    return ServerResponse.createByErrorMessage("参数格式不正确");
                }
            } else if (type == 2) {
                // String tkl = RegUtils.getreGex(str, "￥([a-zA-Z0-9]{11})￥").replace("￥", "");//"￥"+tkl+"￥"
                ServerResponse<TbkItemConvertData> response = TaobaoAnalyzeTkl("￥" + taoKouLing(str) + "￥");
                if (response != null && response.getData() != null) {
                    ResponeResults results = taoBaoMethodService.ItemMethon(response.getData().getNumIid(), userId, null);
                    if (results != null) {
                        return ServerResponse.createBySuccess("数据获取成功", results);
                    } else {
                        return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
                    }
                } else {
//					ResponeResults results = taoBaoMethodService.itemMethon4(str, "tk_total_commi_des ", 1L, 1L, userId, false);
//					if (results != null) {
//						return ServerResponse.createBySuccess("数据获取成功", results);
//					}

                    return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
                }
            } else {
                //默认按照销量倒序
                ServerResponse<List<MapData>> response = SearchSuperTitle(str, "total_sales_des", 1L, 1L, userId, false);
                if (response != null && response.getData() != null) {
                    for (MapData data : response.getData()) {
                        ResponeResults results = taoBaoMethodService.ItemMethon(String.valueOf(data.getNumIid()), userId, null);
                        if (results != null) {
                            return ServerResponse.createBySuccess("数据获取成功", results);
                        } else {
                            return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
                        }
                    }
                } else {
                    return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
                }
                return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
            }
        } else {
            return ServerResponse.createByErrorMessage("参数无效");
        }

    }

    /**
     * 截取链接ID
     *
     * @param href
     * @return
     */
    public static String getTbInnerID(String href) {

        String patternOne = ".*https://item\\.taobao\\.com/item\\.htm\\?id=([0-9]+).*";

        boolean isMatchOne = Pattern.matches(patternOne, href);
        Pattern r = Pattern.compile(patternOne);
        Matcher m = r.matcher(href);

        if (isMatchOne && m.find()) {
            return m.group(1);
        }
        String patternTwo = ".*https://a\\.m\\.taobao\\.com/i([0-9]+)\\.htm\\?.*";

        boolean isMatchTwo = Pattern.matches(patternTwo, href);
        Pattern r2 = Pattern.compile(patternTwo);
        Matcher m2 = r2.matcher(href);

        if (isMatchTwo && m2.find()) {
            return m2.group(1);
        }
        String patternThree = ".*https://detail\\.tmall\\.com/item\\.htm\\?.*&id=([0-9]+).*";

        boolean isMatchThree = Pattern.matches(patternThree, href);
        Pattern r3 = Pattern.compile(patternThree);
        Matcher m3 = r3.matcher(href);

        if (isMatchThree && m3.find()) {
            return m3.group(1);
        }

        String patternFive = ".*https://detail\\.tmall\\.com/item\\.htm\\?id=([0-9]+).*";

        boolean isMatchFive = Pattern.matches(patternFive, href);
        Pattern r5 = Pattern.compile(patternFive);
        Matcher m5 = r5.matcher(href);

        if (isMatchFive && m5.find()) {
            return m5.group(1);
        }
        String patternFour = ".*https://item\\.taobao\\.com/item\\.htm\\?.*&id=([0-9]+).*";

        boolean isMatchFour = Pattern.matches(patternFour, href);
        Pattern r4 = Pattern.compile(patternFour);
        Matcher m4 = r4.matcher(href);

        if (isMatchFour && m4.find()) {
            return m4.group(1);
        }
        return null;
    }

    /**
     * 首页弹窗搜索方法
     * 排序_des（降序），排序_asc（升序），销量（total_sales），淘客佣金比率（tk_rate）， 累计推广量（tk_total_sales），总支出佣金（tk_total_commi）
     *
     * @param str 内容
     * @return popupType1、淘口令弹窗2、淘口令弹框列表3、复制链接弹窗4、复制链接弹框列表5、标题弹框列表
     */
    @Override
    public ServerResponse<ResponeResults> popupSearchNew(String str, Long userId, Long pageNum, Long
            pageSize, String channelUserId) {
        //1好单库->大淘客->联盟
        //截取id
        if (str != null && !"".equals(str)) {
            str = Pattern.compile("\\s*|\t|\r|\n").matcher(str).replaceAll("");
            String tbInnerId = getTbInnerID(str);
            if (tbInnerId != null && RegUtils.isNumeric(tbInnerId)) {
                ResponeResults results = taoBaoMethodService.ItemPopupMethon(tbInnerId, userId, channelUserId);
                if (results == null || results.getData() == null || results.getData().size() <= 0 || results.getData().get(0) == null) {
                    return ServerResponse.createBySuccessCodeMessage(201, "此商品暂无优惠试试其他商品吧~");
                }
                ResponeResults.DataBean dataBean = results.getData().get(0);

                if (dataBean.getHasCoupon() != null && dataBean.getHasCoupon() && dataBean.getFanliMoney() != null
                        && dataBean.getFanliMoney().compareTo(new BigDecimal(0D)) > 0) {
                    results.setPopType("a");
                    results.setPopupType("3");
                    return ServerResponse.createBySuccess("数据获取成功", results);
                } else if (dataBean.getFanliMoney() != null && dataBean.getFanliMoney().compareTo(new BigDecimal(0)) > 0) {
                    results.setPopType("a");
                    results.setPopupType("3");
                    return ServerResponse.createBySuccess("数据获取成功", results);
                } else {
//                    results = taoBaoMethodService.itemMethon4(dataBean.getItemTitle(), "tk_rate_des ", pageSize, pageNum, userId, true, true, channelUserId,"1");
//                    results.setPopType("b");
//                    results.setPopupType("4");
//                    if (results != null) {
//                        return ServerResponse.createBySuccess("数据获取成功", results);
//                    }
                    return ServerResponse.createBySuccessCodeMessage(201, "此商品暂无优惠试试其他商品吧~");
                }
            }

            String tbInnerCode = getTbInnerCode(str);
            if (tbInnerCode != null) {
                //淘口令
                ServerResponse<TbkItemConvertData> response = null;
                AppCompany appCompany = null;
                TaobaoScheme taobaoScheme = null;
                AppUser appUser = null;
                if (userId != null && userId != 0) {
                    appUser = iAppUserService.selectAppUserByUserId(userId, 1);
                    if (appUser != null) {
                        appCompany = appCompanyService.findtAppCompany(appUser.getCompanyId(), 1);
                        if (appUser.getSchemeId() != null && appUser.getSchemeId() != 0) {
                            taobaoScheme = iTaobaoSchemeService.selectTaobaoSchemeById(appUser.getSchemeId(), 1);
                        }
                    }
                }
                if (taobaoScheme == null) {
                    appCompany = appCompanyService.findtAppCompany(null, 1);
                    taobaoScheme = appCompany.getTaoBaoScheme();
                }
                response = TaobaoAnalyzeTklNew(tbInnerCode, appCompany, taobaoScheme);

                if (response != null && response.getData() != null) {

                    ResponeResults results = taoBaoMethodService.ItemPopupMethon(response.getData().getNumIid(), userId, channelUserId);

                    if (results == null || results.getData() == null || results.getData().size() <= 0 || results.getData().get(0) == null) {
                        if (userId == null || appUser == null) {
                            return ServerResponse.createBySuccessCodeMessage(201, "此商品暂无优惠试试其他商品吧~");
                        }
//                        results = taoBaoMethodService.itemMethon4(str, "tk_rate_des ", pageSize, pageNum, userId, true, true, channelUserId,"1");
//                        results.setPopType("b");
//                        results.setPopupType("2");
//                        if (results != null) {
//                            return ServerResponse.createBySuccess("数据获取成功", results);
//                        }
                        return ServerResponse.createBySuccessCodeMessage(201, "此商品暂无优惠试试其他商品吧~");
                    }
//
                    ResponeResults.DataBean dataBean = results.getData().get(0);
                    if (dataBean.getHasCoupon() != null && dataBean.getHasCoupon() && dataBean.getFanliMoney() != null && dataBean.getFanliMoney().compareTo(new BigDecimal(0)) > 0) {
                        results.setPopType("a");
                        results.setPopupType("1");
                    } else if (dataBean.getFanliMoney() != null && dataBean.getFanliMoney().compareTo(new BigDecimal(0)) > 0) {
                        results.setPopType("a");
                        results.setPopupType("1");
                    } else {
//                        results = taoBaoMethodService.itemMethon4(dataBean.getItemTitle(), "tk_rate_des ", pageSize, pageNum, userId, true, true, channelUserId,"1");
//                        results.setPopType("b");
//                        results.setPopupType("2");
//                        if (results != null) {
//                            return ServerResponse.createBySuccess("数据获取成功", results);
//                        }
                        return ServerResponse.createBySuccessCodeMessage(201, "此商品暂无优惠试试其他商品吧~");
                    }
                    return ServerResponse.createBySuccess("数据获取成功", results);

                } else {
                    if (userId == null || appUser == null) {
                        return ServerResponse.createBySuccessCodeMessage(201, "此商品暂无优惠试试其他商品吧~");
                    }
//                    //获取淘口令商品标题
//                    if (str.contains("【") || str.contains("】")) {
//                        String titleStr = str.substring(str.indexOf("【") + 1, str.indexOf("】"));
//                        if (20 <= titleStr.length() && titleStr.length() <= 40 && !titleStr.contains("http")) {
//                            ResponeResults results = taoBaoMethodService.itemMethon4(titleStr, "tk_rate_des ", pageSize, pageNum, userId, true, true, channelUserId,"1");
//                            if (results != null) {
//                                results.setPopType("b");
//                                results.setPopupType("2");
//                                return ServerResponse.createBySuccess("数据获取成功", results);
//                            }
//                        }
//                    }
//                    //按佣金比例倒序
//                    ResponeResults results = taoBaoMethodService.itemMethon4(str, "tk_rate_des ", pageSize, pageNum, userId, true, true, channelUserId,"1");
//                    if (results != null) {
//                        results.setPopType("b");
//                        results.setPopupType("2");
//                        return ServerResponse.createBySuccess("数据获取成功", results);
//                    }
                    return ServerResponse.createBySuccessCodeMessage(201, "此商品暂无优惠试试其他商品吧~");
                }
            }
//            if (20 <= str.length() && str.length() <= 40 && !str.contains("http")) {
//                //标题模糊超级搜索，按照佣金比例
//
//                //按佣金比例倒序
//                ResponeResults results = taoBaoMethodService.itemMethon4(str, "tk_rate_des ", pageSize, pageNum, userId, null, true, channelUserId,"1");
//
//                if (results == null || results.getData() == null || results.getData().size() <= 0 || results.getData().get(0) == null) {
//                    return ServerResponse.createBySuccessCodeMessage(201, "此商品暂无优惠试试其他商品吧~");
//                }
//                if (results.getData().size() == 1) {
//                    ResponeResults.DataBean dataBean = results.getData().get(0);
//                    if ((dataBean.getHasCoupon() != null && dataBean.getHasCoupon())
//                            || dataBean.getFanliMoney().compareTo(new BigDecimal(0)) > 0) {
//
//                        results = taoBaoMethodService.itemMethon4(str, "tk_rate_des ", pageSize, pageNum, userId, null, false, channelUserId,"1");
//                    } else {
//                        results = taoBaoMethodService.itemMethon4(str, "tk_rate_des ", pageSize, pageNum, userId, null, false, channelUserId,"1");
//                        if (results != null && results.getData() != null && results.getData().size() > 0) {
//                            for (ResponeResults.DataBean dataBean1 : results.getData()) {
//                                if (dataBean.getItemId().equals(dataBean1.getItemId())) {
//                                    try {
//                                        results.getData().remove(dataBean1);
//                                    } catch (Exception e) {
//
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//                results.setPopType("c");
//                results.setPopupType("5");
//                return ServerResponse.createBySuccess("数据获取成功", results);
//            }
            return ServerResponse.createByErrorMessage("参数无效");
        } else {
            return ServerResponse.createByErrorMessage("参数无效");
        }
    }

    /**
     * 首页弹窗搜索方法
     * 排序_des（降序），排序_asc（升序），销量（total_sales），淘客佣金比率（tk_rate）， 累计推广量（tk_total_sales），总支出佣金（tk_total_commi）
     *
     * @param str  内容
     * @param type 类型1标题查询2淘口令查询3商品ID查询
     * @return PopType a:精确查找， b,淘口令超级搜索， c,标题模糊搜索
     */
    @Override
    public ServerResponse<ResponeResults> popupSearch(String str, Integer type, Long userId, Long pageNum, Long
            pageSize, String channelUserId) {
        // TODO Auto-generated method Popup
//        AppUserSearchHistory appUserSearchHistory =  new AppUserSearchHistory();
        log.info("首页弹窗   channelUserId=" + channelUserId);
//        String href = "数据线三合一充电线器快充一拖三手机苹果typec通用iPhone6多用功能多头安卓车载三头三线冲两用车用三用带头 https://a.m.taobao.com/i599228661915.htm?sourceType=item&ttid=10001401@taobao_android_9.0.0&ut_sk=1.XUu190dFBX0DANhIT%2BiIk85I_21646297_1574229629841.GoodsTitleURL.1&sm=5e3540 (复制整段信息，打开手机淘宝可直接访问)";


        if (str != null && !"".equals(str) && type == 2 && str.indexOf("m.taobao.com") > -1) {
            String patternTwo = ".*https://a\\.m\\.taobao\\.com/i([0-9]+)\\.htm\\?.*";
            boolean isMatchTwo = Pattern.matches(patternTwo, str);
            Pattern r2 = Pattern.compile(patternTwo);
            Matcher m2 = r2.matcher(str);
            if (isMatchTwo && m2.find()) {
                str = m2.group(1);
                type = 3;
            }
        }
        if (!"".equals(str) && str != null && type != null) {
            if (type == 3) {
                if (str.contains("&")) {
                    str = str.substring(0, str.indexOf("&"));
                    log.info(str);
                }
                if (str.contains("\n")) {
                    str = str.substring(0, str.indexOf("\n")).replaceAll("[^0-9.]", "");
                }
                if (RegUtils.isNumeric(str)) {
//                    ServerResponse<List<NTbkItem>> response = getSearchItemIdDetail(str);
//                    if (response == null || response.getData() == null || response.getData().size() <= 0 && response.getData().get(0) == null) {
//                        return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
//                    }
//                    NTbkItem item = response.getData().get(0);
//
//                    ServerResponse<TbkPrivilege> response2 = getPrivilegeItemId(Long.valueOf(item.getNumIid()), userId);

                    ResponeResults results = taoBaoMethodService.ItemMethon(str, userId, channelUserId);
                    if (results == null || results.getData() == null || results.getData().size() <= 0) {
                        return ServerResponse.createBySuccessCodeMessage(201, "此商品暂无优惠试试其他商品吧~");
                    }
                    ResponeResults.DataBean dataBean = results.getData().get(0);
                    if (pageNum > 1 && dataBean != null) {
                        results = taoBaoMethodService.itemMethon4(dataBean.getItemTitle(), "tk_rate_des ", pageSize, pageNum, userId, true, true, channelUserId, "1");
                        results.setPopType("b");
                        if (results != null) {
                            return ServerResponse.createBySuccess("数据获取成功", results);
                        }
                    }

                    if (dataBean.getHasCoupon() && dataBean.getFanliMoney().compareTo(new BigDecimal(0)) > 0) {
//                        if (userId != null && userId != 0) {
//                            QueryWrapper<AppUserSearchHistory> searchHistoryQueryWrapper = new QueryWrapper<AppUserSearchHistory>();
//                            searchHistoryQueryWrapper.eq("user_id", userId).eq("item_id", dataBean.getItemId());
//                            int count = appUserSearchHistoryService.count(searchHistoryQueryWrapper);
//
//                            if (count <= 0) {
//                                appUserSearchHistory.setUserId(userId);
//                                appUserSearchHistory.setSearchCount(1);
//                                appUserSearchHistory.setItemId(Long.parseLong(dataBean.getItemId()));
//                                appUserSearchHistoryService.save(appUserSearchHistory);
//                            }
//                        }
                        results.setPopType("a");
                        return ServerResponse.createBySuccess("数据获取成功", results);
                    } else if (dataBean.getFanliMoney().compareTo(new BigDecimal(0)) > 0) {
//                        if (userId != null && userId != 0) {
//                            QueryWrapper<AppUserSearchHistory> searchHistoryQueryWrapper = new QueryWrapper<AppUserSearchHistory>();
//                            searchHistoryQueryWrapper.eq("user_id", userId).eq("item_id", dataBean.getItemId());
//                            int count = appUserSearchHistoryService.count(searchHistoryQueryWrapper);
//
//                            if (count <= 0) {
//                                appUserSearchHistory.setUserId(userId);
//                                appUserSearchHistory.setSearchCount(1);
//                                appUserSearchHistory.setItemId(Long.parseLong(dataBean.getItemId()));
//                                appUserSearchHistoryService.save(appUserSearchHistory);
//                            }
//                        }
                        results.setPopType("a");
                        return ServerResponse.createBySuccess("数据获取成功", results);
                    } else {
                        results = taoBaoMethodService.itemMethon4(dataBean.getItemTitle(), "tk_rate_des ", pageSize, pageNum, userId, true, true, channelUserId, "1");
                        results.setPopType("b");
                        if (results != null) {
                            return ServerResponse.createBySuccess("数据获取成功", results);
                        }
                    }
                    return ServerResponse.createBySuccess("数据获取成功", results);

                } else {
                    return ServerResponse.createByErrorMessage("参数格式不正确");
                }
            } else if (type == 2) {

//                AppCompany appCompany = null;
//                if (userId != null && userId != 0) {
//                    appCompany = appCompanyService.findtAppCompany(userId);
//                }
//                if (appCompany == null) {
//                    appCompany = appCompanyService.findCompanyAll();
//                }
//                TaobaoScheme taobaoScheme = null;
//                if (appCompany != null) {
//                    taobaoScheme = appCompany.getTaoBaoScheme();
//                }

//                ServerResponse<TbkItemConvertData> response = TaobaoAnalyzeTklNew("￥" + taoKouLing(str) + "￥", appCompany,taobaoScheme);
                ServerResponse<TbkItemConvertData> response = null; //TaobaoAnalyzeTkl("￥" + taoKouLing(str) + "￥");
                if (response == null || response.getData() == null) {
                    AppCompany appCompany = null;
                    TaobaoScheme taobaoScheme = null;

                    AppUser appUser = null;
                    if (userId != null && userId != 0) {
                        appUser = iAppUserService.selectAppUserByUserId(userId);
                        if (appUser != null) {
                            appCompany = appCompanyService.findtAppCompany(userId);
                            if (appUser.getSchemeId() != null && appUser.getSchemeId() != 0) {
                                taobaoScheme = iTaobaoSchemeService.selectTaobaoSchemeById(appUser.getSchemeId());

                            }
                        }
                    }
                    if (taobaoScheme == null) {
                        appCompany = appCompanyService.findCompanyAll();
                        taobaoScheme = appCompany.getTaoBaoScheme();
                    }
                    response = TaobaoAnalyzeTklNew("￥" + taoKouLing(str) + "￥", appCompany, taobaoScheme);
                }
//                ServerResponse<TbkItemConvertData> response = TaobaoAnalyzeTkl("￥" +str +"￥");
                if (response != null && response.getData() != null) {
                    ResponeResults results = taoBaoMethodService.ItemMethon(response.getData().getNumIid(), userId, channelUserId);

                    if (results == null || results.getData() == null || results.getData().size() <= 0) {
                        results = taoBaoMethodService.itemMethon4(str, "tk_rate_des ", pageSize, pageNum, userId, true, true, channelUserId, "1");
                        results.setPopType("b");
                        if (results != null) {
                            return ServerResponse.createBySuccess("数据获取成功", results);
                        }
                    }
                    if (pageNum > 1 && results.getData().get(0) != null) {
                        results = taoBaoMethodService.itemMethon4(results.getData().get(0).getItemTitle(), "tk_rate_des ", pageSize, pageNum, userId, true, true, channelUserId, "1");
                        results.setPopType("b");
                        if (results != null) {
                            return ServerResponse.createBySuccess("数据获取成功", results);
                        }
                    }
                    ResponeResults.DataBean dataBean = results.getData().get(0);
                    if (dataBean.getHasCoupon() && dataBean.getFanliMoney().compareTo(new BigDecimal(0)) > 0) {
//                        if (userId != null && userId != 0) {
//                            QueryWrapper<AppUserSearchHistory> searchHistoryQueryWrapper = new QueryWrapper<AppUserSearchHistory>();
//                            searchHistoryQueryWrapper.eq("user_id", userId).eq("item_id", dataBean.getItemId());
//                            int count = appUserSearchHistoryService.count(searchHistoryQueryWrapper);
//
//                            if (count <= 0) {
//                                appUserSearchHistory.setUserId(userId);
//                                appUserSearchHistory.setSearchCount(1);
//                                appUserSearchHistory.setItemId(Long.parseLong(dataBean.getItemId()));
//                                appUserSearchHistoryService.save(appUserSearchHistory);
//                            }
//                        }
                        results.setPopType("a");
                    } else if (dataBean.getFanliMoney().compareTo(new BigDecimal(0)) > 0) {
//                        if (userId != null && userId != 0) {
//                            QueryWrapper<AppUserSearchHistory> searchHistoryQueryWrapper = new QueryWrapper<AppUserSearchHistory>();
//                            searchHistoryQueryWrapper.eq("user_id", userId).eq("item_id", dataBean.getItemId());
//                            int count = appUserSearchHistoryService.count(searchHistoryQueryWrapper);
//
//                            if (count <= 0) {
//                                appUserSearchHistory.setUserId(userId);
//                                appUserSearchHistory.setSearchCount(1);
//                                appUserSearchHistory.setItemId(Long.parseLong(dataBean.getItemId()));
//                                appUserSearchHistoryService.save(appUserSearchHistory);
//                            }
//                        }
                        results.setPopType("a");
                    } else {
                        results = taoBaoMethodService.itemMethon4(dataBean.getItemTitle(), "tk_rate_des ", pageSize, pageNum, userId, true, true, channelUserId, "1");
                        results.setPopType("b");
                        if (results != null) {
                            return ServerResponse.createBySuccess("数据获取成功", results);
                        }
                    }
                    return ServerResponse.createBySuccess("数据获取成功", results);

                } else {
                    //按佣金比例倒序
                    ResponeResults results = taoBaoMethodService.itemMethon4(str, "tk_rate_des ", pageSize, pageNum, userId, true, true, channelUserId, "1");
                    if (results != null) {
                        results.setPopType("b");
                        return ServerResponse.createBySuccess("数据获取成功", results);
                    }

                    return ServerResponse.createBySuccessCodeMessage(201, "此商品暂无优惠试试其他商品吧~");
                }
            } else {
                //标题模糊超级搜索，按照佣金比例

                //按佣金比例倒序
                ResponeResults results = taoBaoMethodService.itemMethon4(str, "tk_rate_des ", pageSize, pageNum, userId, null, true, channelUserId, "1");

                if (results == null || results.getData() == null || results.getData().size() <= 0) {
                    return ServerResponse.createBySuccessCodeMessage(201, "此商品暂无优惠试试其他商品吧~");
                }
                if (results.getData().size() == 1) {
                    ResponeResults.DataBean dataBean = results.getData().get(0);
                    if ((dataBean.getHasCoupon() && dataBean.getFanliMoney().compareTo(new BigDecimal(0)) > 0)
                            || dataBean.getFanliMoney().compareTo(new BigDecimal(0)) > 0) {

                        results = taoBaoMethodService.itemMethon4(str, "tk_rate_des ", pageSize, pageNum, userId, null, false, channelUserId, "1");
                    } else {
                        results = taoBaoMethodService.itemMethon4(str, "tk_rate_des ", pageSize, pageNum, userId, null, false, channelUserId, "1");
                        if (results != null && results.getData() != null && results.getData().size() > 0) {
                            for (ResponeResults.DataBean dataBean1 : results.getData()) {
                                if (dataBean.getItemId().equals(dataBean1.getItemId())) {
                                    try {
                                        results.getData().remove(dataBean1);
                                    } catch (Exception e) {

                                    }
                                }
                            }
                        }
                    }
                }
                results.setPopType("c");
                return ServerResponse.createBySuccess("数据获取成功", results);

            }
        } else {
            return ServerResponse.createByErrorMessage("参数无效");
        }

    }

    /**
     * ECO API
     * 超级搜索
     * (高拥转链)
     *
     * @param keyword  商品标题
     * @param sort     排序方式
     * @param pageSize 页大小，默认20，1~100
     * @param pageNo   第几页，默认：１
     * @return https://open.taobao.com/api.htm?docId=35263&docType=2&scopeId=13991
     */
    @Override
    public ServerResponse<List<MapData>> SearchSuperTitle(String keyword, String sort, Long pageSize, Long pageNo,
                                                          Long userId, Boolean hasCoupon) {
        // TODO Auto-generated method SearchSuperTitle
        StringBuilder builder = new StringBuilder();
        TaobaoScheme taobaoScheme = null;
        String generalizePid = "";
        String appSession = "";
        AppUser appUser = iAppUserService.selectAppUserByUserId(userId, 1);
        AppCompany com = appCompanyService.findtAppCompany(appUser == null ? null : appUser.getCompanyId(), 1);
        //用户不为空，推广id不为空时，查询用户对应的推广位
        if (appUser != null && appUser.getSchemeId() != null && appUser.getSchemeId() != 0) {
            taobaoScheme = iTaobaoSchemeService.selectTaobaoSchemeById(appUser.getSchemeId(), 1);
            if (taobaoScheme != null && taobaoScheme.getGeneralizePid() != null && taobaoScheme.getAppSession() != null) {
                generalizePid = taobaoScheme.getGeneralizePid();
                appSession = taobaoScheme.getAppSession();
            }
        }

        //generalizePid或者appSession 为空时，取公司的值
        if ((generalizePid == null || "".equals(generalizePid)) || (appSession == null || "".equals(appSession))) {
            generalizePid = com.getGeneralizePid();
            appSession = com.getTaoBaoScheme().getAppSession();
        }

        builder.append("session=").append(appSession);
        builder.append("&keyword=").append(keyword);
        builder.append("&adzoneId=").append(generalizePid.split("_")[3]);
        builder.append("&siteId=").append(generalizePid.split("_")[2]);
        builder.append("&sort=").append(sort);
        builder.append("&pageSize=").append(pageSize == null ? 20 : pageSize);
        builder.append("&pageNo=").append(pageNo == null ? 1 : pageNo);
        builder.append("&hasCoupon=").append(hasCoupon);

        TbkScMaterialOptionalResponse tbkScMaterialOptionalResponse = searchController.orderDetails(appSession, keyword, Long.parseLong(generalizePid.split("_")[3]),
                Long.parseLong(generalizePid.split("_")[2]), sort, pageSize, pageNo, hasCoupon
        );
        String str = "";
        log.info("第一次调用orderDetails{}--", keyword);
        if ("50001".equals(tbkScMaterialOptionalResponse.getSubCode())) {
            log.info("50001第二次调用orderDetails{}--", keyword);
            tbkScMaterialOptionalResponse = searchController.orderDetails(appSession, keyword, Long.parseLong(generalizePid.split("_")[3]),
                    Long.parseLong(generalizePid.split("_")[2]), sort, pageSize, pageNo, hasCoupon
            );
        }
        if (tbkScMaterialOptionalResponse != null) {
            str = JSON.toJSONString(tbkScMaterialOptionalResponse);
        }

//        String str = ApiUtils.postSuperTitle(ApiEnum.TAOBAO_ITEM_OPTIONAL, builder.toString());


        log.info("获取到超级搜索商品详情：{}", str);
        if (str == null) {
            return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
        } else {
            TbkScMaterialOptionalInfo response = JsonUtils.getJsonToBean(str, TbkScMaterialOptionalInfo.class);
            if (response.isSuccess()) {
                return ServerResponse.createBySuccess("数据获取成功", response.getResultList());
            } else {
                return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
            }
        }
    }


    /**
     * 维意接口API
     * 获取店铺评分 店铺信息
     */
//	@Override
//	public WeiYiInfo getShopMessage(String itemId,String shopType) {
//		// TODO Auto-generated method getShopMessage
//		//http://apipro.vephp.com/itemdetail?vekey=V00001043Y60238823&para=587697102297&shoptype=C&moreinfo=1
//		StringBuilder builder = new StringBuilder();
//		builder.append("&para=").append(itemId);
//		builder.append("&shoptype=").append(shopType);
//		builder.append("&moreinfo=").append("1");
//		String str = ApiUtils.getWYData(ApiEnum.WEIYI_ITEMDETAIL, builder.toString());
//		log.info("获取到商品详情：{}",str);
//		WeiYiInfo info = JsonUtils.getJsonToBean(str, WeiYiInfo.class);
//		if(RegUtils.getreGex(str, "error\"\\:1") == null) {
//			//log.info("获取到商品店铺详情：{}",info.getData().getSeller().getShopId());
//			AppGoodsShopdrs shopdrs = iAppGoodsShopdrsService.selectAppGoodsShopdrsByShopId(info.getData().getSeller().getShopId());
//			if(shopdrs != null && shopdrs.getWyItemDetail() != null) {
//				WeiYiInfo info2 = JsonUtils.getJsonToBean(shopdrs.getWyItemDetail(), WeiYiInfo.class);
//				return info2;
//			}else {
//				AppGoodsShopdrs appGoodsShopdrs = new AppGoodsShopdrs();
//				appGoodsShopdrs.setItemId(Long.valueOf(itemId));
//				appGoodsShopdrs.setShopId(Long.valueOf(info.getData().getSeller().getShopId()));
//				appGoodsShopdrs.setShopName(info.getData().getSeller().getShopName());
//				appGoodsShopdrs.setWyItemDetail(JsonUtils.getBeanToJson(info).toString());
//				iAppGoodsShopdrsService.insertAppGoodsShopdrs(appGoodsShopdrs);
//			}
//			return info;
//		}else {
//			return null;
//		}
//	}

    /***
     * 高佣转链后返回URL
     */
    @Override
    public ServerResponse<String> getPrivilegeItemURL(String itemId, Long userId, Integer jumpType, String
            activityid) {
        // TODO Auto-generated method getPrivilegeItemURL
        ServerResponse<TbkPrivilege> response = getPrivilegeItemId(NumberUtils.toLong(itemId), userId, jumpType);
        if (response != null && response.getData() != null) {
            if (!StringUtils.isEmpty(activityid)) {
                String couponClickUrl = response.getData().getCouponClickUrl() + "&activityId=" + activityid;
                return ServerResponse.createBySuccess("数据获取成功", couponClickUrl);
            } else {
                if (response.getData().getCouponInfo() == null) {
                    return ServerResponse.createBySuccess("数据获取成功", response.getData().getItemUrl());
                } else {
                    return ServerResponse.createBySuccess("数据获取成功", response.getData().getCouponClickUrl());
                }
            }

        } else {
            return ServerResponse.createByErrorMessage("该商品已失效");
        }
    }

    /***
     * 免单高佣转链后返回URL
     */
    @Override
    public ServerResponse<String> getPrivilegeGoodsFreeItemURL(String itemId, Long userId, Integer jumpType, String
            type, String activityid) {
        // TODO Auto-generated method getPrivilegeItemURL
        long goodsId = NumberUtils.toLong(itemId);
        if (!StringUtils.isEmpty(type) && "2".equals(type)) {
            GoodsFreeIntegral goodsFreeIntegral = goodsFreeIntegralMapper.selectByGoodsId(goodsId);
            if (StringUtils.isEmpty(goodsFreeIntegral)) {
                return ServerResponse.createByErrorMessage("此商品在积分兑换商品库不存在！");
            }
        } else {
            //判断数量问题
        /*List<AppGoods> appGoods = iAppGoodsService.selectAppGoodsByItemId(goodsId);
        if (CollectionUtils.isEmpty(appGoods)) return ServerResponse.createByErrorMessage("此商品在商品库不存在！");*/
            GoodsFree goodsFree = iGoodsFreeService.selectByGoodsId(goodsId);
            if (StringUtils.isEmpty(goodsFree)) {
                return ServerResponse.createByErrorMessage("此商品在免单商品库不存在！");
            }
            if (goodsFree.getNumber() <= 0) {
                return ServerResponse.createByErrorMessage("此商品已经抢完了！");
            }
        }
        //判断佣金比率低于70%
       /* AppGoods appGoods1 = appGoods.get(0);
        if (!StringUtils.isEmpty(appGoods1.getTkrates())) {
            if (Double.valueOf(appGoods1.getTkrates()) < 70.00){
                GoodsFree goodsFree1 = new GoodsFree();
                goodsFree1.setGoodsId(goodsFree.getGoodsId());
                goodsFree1.setGoodsStatus(1);
                iGoodsFreeService.updateGoodsStausByGoodsFree(goodsFree1);
                return ServerResponse.createByErrorMessage("您不能购买该商品（佣金问题）");
            }
        }*/
        ServerResponse<TbkPrivilege> response = getPrivilegeItemId(goodsId, userId, jumpType);

        if (response != null && response.getData() != null) {
            if (!StringUtils.isEmpty(activityid)) {
                String couponClickUrl = response.getData().getCouponClickUrl() + "&activityId=" + activityid;
                return ServerResponse.createBySuccess("数据获取成功", couponClickUrl);
            } else {
                if (response.getData().getCouponInfo() == null) {
                    return ServerResponse.createBySuccess("数据获取成功", response.getData().getItemUrl());
                } else {
                    return ServerResponse.createBySuccess("数据获取成功", response.getData().getCouponClickUrl());
                }
            }
        } else {
            return ServerResponse.createByErrorMessage("该商品已失效");
        }
    }


    /**
     * 淘宝API 猜你喜欢  调用方法
     *
     * @param itemId
     * @param deviceValue
     * @param deviceEncrypt
     * @param deviceType
     * @param pageSize
     * @param pageNo
     * @param userId
     * @return
     */
    @Override
    public ServerResponse<ResponeResults> getSimilarInfoMethon(
            String itemId, String deviceValue, String deviceEncrypt, String deviceType, Long pageSize, Long pageNo,
            Long userId) {
        // TODO Auto-generated method getSimilarInfoMethon
        ResponeResults results = taoBaoMethodService.OptimusMaterial(
                NumberUtils.toLong(itemId), deviceValue, deviceEncrypt, deviceType, pageSize, pageNo, userId);
        if (results != null) {
            return ServerResponse.createBySuccess("数据获取成功", results);
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "没有更多商品");
        }
    }

    /**
     * 获取我的订单
     *
     * @param tkStatus
     * @param pageNum
     * @param pageSize
     * @param userId
     * @return
     */
    @Override
    public ServerResponse<List<OrderDataBean>> getMeOrderDetail(Integer tkStatus,
                                                                Integer pageNum, Integer pageSize, Long userId, String orderType, String version) {
        // TODO Auto-generated method getMeOrderDetail
        List<AppOrderDetailVo> details = null;
        pageNum = pageNum == null ? 0 : pageNum;
        pageSize = pageSize == null ? 20 : pageSize;
        List<OrderDataBean> orderResults = null;
        if ("1".equals(orderType) || com.eco.fanliapp.utils.StringUtils.isNull(orderType)) {
            orderResults = taoBaoMethodService.getMeOrderDetailMethon(tkStatus, pageNum, pageSize, userId, orderType, version);

        } else if ("2".equals(orderType)) {
            orderResults = taoBaoMethodService.getJdOrderDetailMethon(tkStatus, pageNum, pageSize, userId, orderType, version);

        } else if ("3".equals(orderType)) {
            orderResults = taoBaoMethodService.getPddOrderDetailMethon(tkStatus, pageNum, pageSize, userId, orderType, version);
        }

        if (orderResults != null && orderResults.size() > 0) {
            return ServerResponse.createBySuccess("数据获取成功", orderResults);
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "没有更多订单");
        }
    }

    /**
     * 获取我的收益-入账中订单-包含自己订单，直接粉丝订单，间接粉丝订单，分享赚订单     tkStatus = 12
     *
     * @param tkStatus
     * @param pageNum
     * @param pageSize
     * @param userId
     * @return
     */
    @Override
    public ServerResponse<List<OrderDataBean>> getMeBookedOrderDetail(Integer tkStatus,
                                                                      Integer pageNum, Integer pageSize, Long userId) {
        List<OrderDataBean> orderResults = taoBaoMethodService.getMeBookedOrderDetail(tkStatus, pageNum, pageSize, userId);
        if (orderResults != null) {
            return ServerResponse.createBySuccess("数据获取成功", orderResults);
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "没有更多订单");
        }
    }

    //根据订单ID获取详情
    @Override
    public ServerResponse<List<OrderDataBean>> findOrderIdDetail(String orderId, Long userId) {
        // TODO Auto-generated method findOrderIdDetail
        Long o = NumberUtils.toLong(orderId);
        List<OrderDataBean> orderResults = taoBaoMethodService.getOrderIdDetailMethon(o, userId);
        if (orderResults != null) {
            return ServerResponse.createBySuccess("数据获取成功", orderResults);
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "没有更多订单");
        }
    }

    //朋友圈
    @Override
    public ServerResponse<List<ResponeFriendsResults>> getFriends(
            Integer start, Integer back, Long userId, Integer companyId) {
        // TODO Auto-generated method getFriends
        List<WebCircleFriends> webCircleFriends =
                iWebCircleFriendsService.selectWebCircleFriendsListsLIMIT(start, back, companyId);
        if (webCircleFriends.size() > 0) {
            List<ResponeFriendsResults> friendsResults = new ArrayList<ResponeFriendsResults>();
            Integer s = ApiEnum.YOUKEMODE;//游客模式的佣金
            for (WebCircleFriends webCircleFriends2 : webCircleFriends) {
                ResponeFriendsResults results = new ResponeFriendsResults();
                if (null != userId && 0 != userId) {
                    s = iUserCashschemeService.getCommissionRate(userId,
                            webCircleFriends2.getShareMoney().doubleValue());
                    ServerResponse<String> response = getPrivilegeItemURL(webCircleFriends2.getItemid(), userId, null, null);
                    if (response != null && response.getStatus() == 200) {
                        String key = "" + userId + webCircleFriends2.getItemid() + companyId;
                        String tkl = "";
                        if (redisTemplate.hasKey(key)) {
                            tkl = (String) redisTemplate.opsForValue().get(key);
                        } else {
                            tkl = ApiEnum.O_TKL_O[0]
                                    + TaobaoCreateTkl(webCircleFriends2.getTitle(),
                                    webCircleFriends2.getItemMainImageUrl(),
                                    response.getData(), userId).getData() == null ? "" :
                                    TaobaoCreateTkl(webCircleFriends2.getTitle(),
                                            webCircleFriends2.getItemMainImageUrl(),
                                            response.getData(), userId).getData().replace("￥", "") +
                                            ApiEnum.O_TKL_O[1];
                            redisTemplate.opsForValue().set(key, tkl, 1, TimeUnit.DAYS);
                        }
//							results.setComments(webCircleFriends2.getComments()+tkl);

                        results.setComments(webCircleFriends2.getTitle() + "\n" + tkl
                                + "\n复\uE437制本条<:-16,-97,-115,-119:>评论"
                                + "\n然后咑开【手\uE32E机掏宝】即可领券\n"
                        );
                    } else {
                        results.setComments(webCircleFriends2.getComments());
                    }
                } else {
                    results.setComments(webCircleFriends2.getComments());
                }
                results.setComments(EmojiUtil.resolveToEmojiFromByte(results.getComments()));
                results.setTableId(webCircleFriends2.getTableId());
                results.setFriendName(EmojiUtil.resolveToEmojiFromByte(webCircleFriends2.getFriendName()));
//					results.setFriendName(webCircleFriends2.getFriendName());
                results.setUserName(webCircleFriends2.getUserName());
                results.setUserIconUrl(webCircleFriends2.getUserIconUrl());
                results.setItemMainImageUrl(webCircleFriends2.getItemMainImageUrl());
                results.setItemImageUrl(webCircleFriends2.getItemImageUrls());
                results.setTitle(EmojiUtil.resolveToEmojiFromByte(webCircleFriends2.getTitle()));
//					results.setTitle(webCircleFriends2.getTitle());
                results.setItemid(webCircleFriends2.getItemid());
                results.setFriendsGuideUrl(webCircleFriends2.getFriendsGuideUrl());
                results.setForwardingNumber(webCircleFriends2.getForwardingNumber());
                results.setCreateTime(webCircleFriends2.getCreateTime());
                results.setGoodsBuyUrl(webCircleFriends2.getGoodsBuyUrl());
                results.setShareUrl(webCircleFriends2.getShareUrl());
                results.setShareMoney(BigDecimalUtils.FanliMoney(s.toString(), webCircleFriends2.getShareMoney()));
                results.setGoodsStatus(webCircleFriends2.getGoodsStatus());
                friendsResults.add(results);
            }
            return ServerResponse.createBySuccess("数据获取成功", friendsResults);
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "暂无更多数据");
        }
    }

    @Override
    public void getFriendsCount(Long itemId) {
        // TODO Auto-generated method getFriendsCount 朋友圈分享次数自动加
        //查询当前评论数
        WebCircleFriends friends = iWebCircleFriendsService.selectWebCircleFriendsByitemid(itemId);
        //设置当前评论数加一
        if (friends != null) {
            WebCircleFriends webCircleFriends = new WebCircleFriends();
            webCircleFriends.setForwardingNumber(friends.getForwardingNumber() + 1);
            webCircleFriends.setTableId(friends.getTableId());
            int i = iWebCircleFriendsService.updateWebCircleFriendsCount(webCircleFriends);
            if (i > 0) {
                log.info("朋友圈分享成功{}次数{}", i, webCircleFriends.getForwardingNumber());
            } else {
                log.info("朋友圈分享失败{}次数{}", i);
            }
        } else {
            log.info("message无数据");
        }
    }

    //朋友圈分享次数2
    @Override
    public ServerResponse<String> getFriendsCount2(Long fid) {
        // TODO Auto-generated method getFriendsCount2
        if (!StringUtils.isEmpty(fid)) {
            //查询当前评论数
            WebCircleFriends friends = iWebCircleFriendsService.selectWebCircleFriendsById(fid);
            //设置当前评论数加一
            WebCircleFriends webCircleFriends = new WebCircleFriends();
            webCircleFriends.setForwardingNumber(friends.getForwardingNumber() + 1);
            webCircleFriends.setTableId(friends.getTableId());
            int i = iWebCircleFriendsService.updateWebCircleFriendsCount(webCircleFriends);
            if (i > 0) {
                log.info("朋友圈分享成功{}次数{}", i, webCircleFriends.getForwardingNumber());
                return ServerResponse.createBySuccess("数据获取成功", webCircleFriends.getForwardingNumber().toString());
            } else {
                log.info("朋友圈分享失败{}次数{}", i);
                return ServerResponse.createByErrorCodeMessage(500, "分享失败");
            }
        } else {
            return ServerResponse.createByErrorMessage("未传入朋友圈ID");
        }
    }

    //超级搜索的返回方法
    @Override
    public ServerResponse<ResponeResults> ReturnSearchSuperTitle(String keyword, String sort, Long pageSize,
                                                                 Long pageNo, Long userId, Boolean hasCoupon, String channelUserId, String version, String type) {
        // TODO Auto-generated method ReturnSearchSuperTitle
//        if (StringUtils.isEmpty(sort)) {
//            sort = "tk_total_commi_des";
//        }
        ResponeResults results = taoBaoMethodService.itemMethon4(keyword, sort, pageSize, pageNo, userId, hasCoupon, false, null, type);
        if (results != null) {
            long sysTime = System.currentTimeMillis();
            if (StringUtils.isEmpty(version)) {
                for (ResponeResults.DataBean dataBean : results.getData()) {
                    if (Long.valueOf((dataBean.getCouponStartTime() == null || "".equals(dataBean.getCouponStartTime()) || dataBean.getCouponStartTime().indexOf("null") > -1) ? "0" : dataBean.getCouponStartTime()) > sysTime) {
                        dataBean.setCouponStartTime(String.valueOf(Long.valueOf(dataBean.getCouponStartTime() == null ? "" : dataBean.getCouponStartTime()) - sysTime));
                        dataBean.setCouponEndTime(null);
                    } else {
                        dataBean.setCouponStartTime(null);
                        if (Long.valueOf((dataBean.getCouponEndTime() == null || "".equals(dataBean.getCouponEndTime()) || dataBean.getCouponEndTime().indexOf("null") > -1) ? "0" : dataBean.getCouponEndTime()) > sysTime) {
                            dataBean.setCouponEndTime(String.valueOf(Long.valueOf(dataBean.getCouponEndTime() == null ? "0" : dataBean.getCouponEndTime()) - sysTime));
                        } else {
                            dataBean.setCouponEndTime(null);
                        }
                    }
                }
            }
            return ServerResponse.createBySuccess("获取商品成功", results);
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "未搜到此商品");
        }
    }

    //超级搜索的返回方法
    @Override
    public ServerResponse getDaTaoKeSearchGoods(String keyword, String sort, Long pageSize,
                                                String pageNum, Long userId, String channelUserId) {
        //排序字段信息 销量（total_sales） 价格（price），排序_des（降序），排序_asc（升序）
        if (keyword != null) {
            keyword = keyword.replaceAll("\\s*", ""); //可以替换大部分空白字符， 不限于空格 ；
        }
        if (sort != null) {
            sort = sort.replaceAll("\\s*", ""); //可以替换大部分空白字符， 不限于空格 ；
        }
        String result = daTaoKeItemInfoService.getDaTaoKeSearchGoods(keyword, sort, pageSize, pageNum);
        List<DTKResponse.DataBean> response = null;
        if (result != null) {
            result = com.alibaba.fastjson.JSONObject.parseObject(result).getString("data");
            if (result != null) {
                result = com.alibaba.fastjson.JSONObject.parseObject(result).getString("list");
            } else {
                return ServerResponse.createBySuccessCodeMessage(201, "未搜到此商品");
            }
            if (result != null) {
                response = JsonUtils.getJsonToList(result, DTKResponse.DataBean.class);
            }
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "未搜到此商品");
        }
        List goodsList = new ArrayList<>();
        long sysTime = System.currentTimeMillis();
        if (response != null) {
            for (DTKResponse.DataBean item : response) {
                AppGoods goods = HDKUtils.getAppGoodsFromDTK(item);
                if (Long.valueOf((goods.getCouponstarttime() == null || "".equals(goods.getCouponstarttime()) || goods.getCouponstarttime().indexOf("null") > -1) ? "0" : goods.getCouponstarttime()) > sysTime) {
                    goods.setCouponstarttime(String.valueOf(Long.valueOf(goods.getCouponstarttime() == null ? "" : goods.getCouponstarttime()) - sysTime));
//                    goods.setCouponendtime(null);
                } else {
//                    goods.setCouponstarttime(null);
                    if (Long.valueOf((goods.getCouponendtime() == null || "".equals(goods.getCouponendtime()) || goods.getCouponendtime().indexOf("null") > -1) ? "0" : goods.getCouponendtime()) > sysTime) {
                        goods.setCouponendtime(String.valueOf(Long.valueOf(goods.getCouponendtime() == null ? "0" : goods.getCouponendtime()) - sysTime));
                    } else {
                        goods.setCouponendtime(null);
                    }
                }
                if (goods.getItempic() != null) {
                    goods.setItempic(goods.getItempic().replaceAll(".jpg", ".jpg_200x200.jpg"));
                }
                goodsList.add(goods);
            }
            ResponeResults results = goodsScheme(userId, goodsList, channelUserId);
            return ServerResponse.createBySuccess("获取商品成功", results);
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "未搜到此商品");
        }
    }

    //首页数据返回
    @Override
    public ServerResponse<ResponeResults> getClassifyItemList(Integer type, Integer start, Integer back,
                                                              Integer cid, Integer recommend, Integer sort, Long userId, Boolean free, Integer companyId) {
        // TODO Auto-generated method getClassifyItemList
        ResponeResults results = taoBaoMethodService.ItemMethon5(type, start, back, cid, recommend, sort, userId, free, companyId);
        if (results != null) {
            return ServerResponse.createBySuccess("数据获取成功", results);
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "没有更多商品");
        }
    }

    //获取免单商品
    @Override
    public ServerResponse<ResponeResults> getGoodsFreeList(
            Integer type, Integer cid, Integer pageNum, Integer pageSize, Long userId, Integer companyId) {
        // TODO Auto-generated method getGoodsFreeList
        ResponeResults results = taoBaoMethodService.ItemMethon8(type, cid, pageNum, pageSize, userId, companyId);
        if (results != null) {
            return ServerResponse.createBySuccess("数据获取成功", results);
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "没有更多商品");
        }
    }

    @Override
    public ServerResponse<ResponeResults> getSalesList() {
        // TODO Auto-generated method getSalesList 获取榜单商品
        StringBuilder param = new StringBuilder();
        param.append("sale_type/").append(1);//实时榜单
        param.append("/cid/").append(0);
        param.append("/min_id/").append(1);
        param.append("/back/").append(100);
        String str = ApiUtils.getData(ApiEnum.SALES_LIST, param.toString());
        HaoDanKuSearchInfo info = JsonUtils.getJsonToBean(str, HaoDanKuSearchInfo.class);
        if (info != null && info.getCode() == 1 && info.getData().size() > 0) {
            ResponeResults results = taoBaoMethodService.ItemMethon2(info, null);
            if (results != null) {
                return ServerResponse.createBySuccess("数据获取成功", results);
            } else {
                return ServerResponse.createBySuccessCodeMessage(201, "没有更多商品");
            }
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "没有更多商品");
        }
    }

    //商品搜索匹配列表
    @Override
    public ServerResponse findKeyword(String keyword) {
        try {

            String data = restTemplate.postForObject("http://service-provider" + "/eureke/lucene/findKeyword?keyword=" + keyword, null, String.class);
            Map map = new HashMap<>();
            if (data != null || data != "") {
//                JSONObject object = JSONObject.parseObject(data);
                JSONArray array = JSONArray.parseArray(data);
                List<String> list = JsonUtils.getJsonToList(array.toJSONString(), String.class);
                if (list != null) {
                    map.put("matchList", list);
                    return ServerResponse.createBySuccess(200, "获取本地商品成功", map);
                } else {
                    return ServerResponse.createBySuccessCodeMessage(201, "没有更多商品");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ServerResponse.createByErrorCodeMessage(201, "获取本地商品失败");

    }

    //搜索商品
    @Override
    public ServerResponse SearchLocalGoods(String keyword, String sort, Integer pageSize, Integer pageNum, Long
            userid, String fqcat, String channelUserId) {

        // 排序方式默认按销量排序 排序_des（降序），排序_asc（升序），销量（total_sales），淘客佣金比率（tk_rate），价格（price）
        try {

//            String data = restTemplate.postForObject("http://service-provider" + "/eureke/lucene/findIndex?keyword=" + keyword + "&sort=" + sort + "&pageNum=" + pageNum + "&pageSize=" + pageSize + "&fqcat=" + "", null, String.class);
//            Map map = new HashMap<>();
//            if (data != null || data != "") {
//                String pages = JSONObject.parseObject(data).getString("pages");
//                data = JSONObject.parseObject(data).getString("records");
//                List<AppGoods> list = JSONObject.parseArray(data, AppGoods.class);
//                List<AppGoodsVo> appGoodsVoList = getAppGoodsVo(userid, list, null, channelUserId);
//                if (Integer.valueOf(pages) > 2) {
//                    pages = "2";
//                }
//                if (Integer.valueOf(pages) <= pageNum) {
//                    map.put("min_id", 0);
//                    map.put("data", appGoodsVoList);
//                    return ServerResponse.createBySuccess(200, "没有更多商品数据，请获取全网搜索结果", map);
//                } else {
//                    if (appGoodsVoList != null) {
//                        map.put("min_id", 1);
//                        map.put("data", appGoodsVoList);
//                        return ServerResponse.createBySuccess(200, "获取本地商品成功", map);
//                    }
//                }
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ServerResponse.createByErrorCodeMessage(201, "获取本地商品失败");
    }

    @Override
    public ServerResponse getRecommendGoodsNew(Integer pageSize, Integer pageNum, Long userid, String
            channelUserId, String version) {
        String key = "app_recommendGoodsLists_" + pageNum;
//        List<AppGoods> goodsList = null;
        String tljKey = "TljGoodsfree_title";
        Map map = new HashMap<>();
//
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        calendar.setTime(new Date());
        int time = calendar.get(java.util.Calendar.HOUR_OF_DAY);
        int count = 0;
        if (redisTemplateService.hasKey("app_tlj_channel_count")) {
            count = redisTemplateService.getInt("app_tlj_channel_count");
        }
//
//        //添加图片标签 0 5 10 15...
//        Map<String, Object> stringObjectMap = goodsImageLableService.selectGoodsImageLable();
//        if (redisTemplateService.hasKey(key)) {
//            if (pageNum <= 2) {
//                goodsList = redisTemplateService.getTByListKey(key, AppGoods.class);
//            }
//        } else {
//            //分页
//            Integer start = (pageNum - 1) * pageSize;
//            Integer end = pageSize;
//            log.info("查询推荐商品");
//            goodsList = appGoodsMapper.selectRecommendGoods(start, end);
//            if (goodsList != null && goodsList.size() > 0) {
//                String fixedSort_key = "app_fixedSortGoods_list";
//                if (redisTemplateService.hasKey(fixedSort_key)) {
//                    Map<String, Integer> fixedSortMap = redisTemplateService.getMap(fixedSort_key, Map.class);
//                    for (String sortKey : fixedSortMap.keySet()) {
//                        AppGoods appGoods = appGoodsMapper.findAppGoodsByItemId(sortKey);
//                        for (int i = 0; i <= goodsList.size() - 1; i++) {
//                            if (goodsList.get(i).getItemid().equals(sortKey)) {
//                                goodsList.remove(goodsList.get(i));
//                                break;
//                            }
//                        }
//                        if (appGoods != null) {
//                            if (pageNum == 1) {
//                                goodsList.add(fixedSortMap.get(sortKey) - 1, appGoods);
//                            }
//                        }
//
//                    }
//                }
//            }
//            if (pageNum <= 2) {
//                if (stringObjectMap != null) {
//                    if (stringObjectMap.containsKey("festivalLable") && stringObjectMap.containsKey("festivalSeckill")) {
//                        int num = 0;
//                        for (int i = 0; i < goodsList.size(); i++) {
//                            if (i == num) {
//                                goodsList.get(i).setLableUrl(stringObjectMap.get("festivalSeckill").toString());
//                                num += 5;
//                            } else {
//                                goodsList.get(i).setLableUrl(stringObjectMap.get("festivalLable").toString());
//                            }
//                        }
//                    } else if (stringObjectMap.containsKey("commonLable") && stringObjectMap.containsKey("commonSeckill")) {
//                        int num = 0;
//                        for (int i = 0; i < goodsList.size(); i++) {
//                            if (i == num) {
//                                goodsList.get(i).setLableUrl(stringObjectMap.get("commonSeckill").toString());
//                                num += 5;
//                            } else {
//                                goodsList.get(i).setLableUrl(stringObjectMap.get("commonLable").toString());
//                            }
//                        }
//                    }
//                }
//                if (pageNum == 1) {
//                    //淘礼金等 加到第一页
////                    List<AppGoods> itemtopAppGoods = appGoodsMapper.selectItemtopAll();
//                    List<AppGoods> tljAppGoods = appGoodsMapper.selectTljGoods();
//                    List<AppGoods> channelAppGoods = appGoodsMapper.selectChannelGoods();
//                    List<AppGoods> newList = new ArrayList<>();
//                    if (tljAppGoods != null) {
//                        newList.addAll(tljAppGoods);
//                    }
//                    if (channelAppGoods != null) {
//                        newList.addAll(channelAppGoods);
//                    }
////                    if (itemtopAppGoods != null) {
////                        newList.addAll(itemtopAppGoods);
////                    }
//                    newList.addAll(goodsList);
//                    goodsList.clear();
//                    goodsList = newList;
//                }
//            } else {
//                if (stringObjectMap != null) {
//                    if (stringObjectMap.containsKey("festivalLable") && stringObjectMap.containsKey("festivalSeckill")) {
//                        for (int i = 0; i < goodsList.size(); i++) {
//                            goodsList.get(i).setLableUrl(stringObjectMap.get("festivalLable").toString());
//                        }
//                    } else if (stringObjectMap.containsKey("commonLable") && stringObjectMap.containsKey("commonSeckill")) {
//                        for (int i = 0; i < goodsList.size(); i++) {
//                            goodsList.get(i).setLableUrl(stringObjectMap.get("commonLable").toString());
//                        }
//                    }
//                }
//            }
//            if (pageNum <= 2) {
//                redisTemplateService.set(key, goodsList, 60 * 5);
//            }
//        }
        List<AppGoods> goodsList = null;
        if (redisTemplateService.hasKey(key)) {
            goodsList = redisTemplateService.getTByListKey(key, AppGoods.class);
        } else {
            List<AppGoods> appGoodsList = appGoodsMapper.selectRecommendGoodsAll();
            getRedisRecommendGoodsList(appGoodsList);
            goodsList = redisTemplateService.getTByListKey(key, AppGoods.class);
        }
        int num = 0;
        if (goodsList != null && goodsList.size() > 0) {
            List<AppGoodsVo> appGoodsVoList = getAppGoodsVo(userid, goodsList, null, channelUserId, version);
            for (AppGoodsVo appGoodsVo : appGoodsVoList) {
                num++;
                if (time >= 10 && pageNum < 4) {
                    appGoodsVo.setMsg("上新");
                }
                if (time >= 10 && pageNum == 4 && num <= 30 + count) {
                    appGoodsVo.setMsg("上新");
                }
                if (appGoodsVo != null && appGoodsVo.getItemTop() == 7) {
                    if (redisTemplateService.hasKey(tljKey)) {
                        appGoodsVo.getLabelTypeTitle().add(redisTemplateService.getStr(tljKey));
                    } else {
                        appGoodsVo.getLabelTypeTitle().add("0元购—社群专享");
                        redisTemplateService.set(tljKey, "0元购—社群专享", 0);
                    }
                    SyTljGoodsfree syTljGoodsfree = iSyTljGoodsfreeMapper.selectTljGoodsfreeByItemId(Long.valueOf(appGoodsVo.getItemId()));
                    if (syTljGoodsfree != null && syTljGoodsfree.getFailureTime() != null) {
                        appGoodsVo.setTljEndTime("结束时间：" + DateFormatUtils.dateToString(syTljGoodsfree.getFailureTime()));
                    }
                }
                if (appGoodsVo != null && appGoodsVo.getItemTop() == 8) {
                    appGoodsVo.setItemShortTitle(appGoodsVo.getItemShortTitle() + "【限补贴1单】");
                    appGoodsVo.getLabelTypeTitle().add("限时漏洞");
                }
                if (!StringUtils.isEmpty(appGoodsVo.getMsg())) {
                    appGoodsVo.getLabelTypeTitle().add(appGoodsVo.getMsg());
                }
                if (!StringUtils.isEmpty(appGoodsVo.getLabelName())) {
                    List<String> labelNameList = Arrays.asList(Convert.toStrArray(appGoodsVo.getLabelName()));
                    if (labelNameList != null && labelNameList.size() != 0) {
//                        if (labelNameList.contains("旗舰店")) {
//                            appGoodsVo.getLabelTypePicture().add("旗舰店");
//                        }
                        if (labelNameList.contains("金牌卖家")) {
                            appGoodsVo.getLabelTypeContent().add("金牌卖家");
                        }
                        if (labelNameList.contains("淘抢购")) {
                            appGoodsVo.getLabelTypeTitle().add("淘抢购");
                        }
                        if (labelNameList.contains("聚划算")) {
                            appGoodsVo.getLabelTypeTitle().add("聚划算");
                        }
                        if (labelNameList.contains("淘淘商品")) {
                            appGoodsVo.getLabelTypeContent().add("淘淘商品");
                        }
                        if (labelNameList.contains("品牌产品")) {
                            appGoodsVo.getLabelTypeContent().add("品牌产品");
                        }
                        if (labelNameList.contains("天猫超市")) {
                            appGoodsVo.getLabelTypeContent().add("天猫超市");
                        }
                        if (labelNameList.contains("历史最低价")) {
                            appGoodsVo.getLabelTypeContent().add("历史最低价");
                        }
                    }
                }
            }

            map.put("min_id", null);
            map.put("data", appGoodsVoList);
            log.info("查询推荐商品成功", appGoodsVoList);
            return ServerResponse.createBySuccess("数据获取成功", map);
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "没有更多商品");
        }
    }


    //获取商品列表--废弃
    @Override
    public ServerResponse getClassifyGoodsList(Integer pageSize, Integer pageNum, Integer cid, String sort, Integer
            type, Long userid, String channelUserId) {
        log.info("查询商品列表", "pageSize:" + pageSize, "pageNum:" + pageNum, "cid:" + cid, "sort:" + sort, "type:" + type, "userid:" + userid);
        //推荐 recommend，销量 sales，最新 latest ，价格 price_desc/price_asc

        QueryWrapper<AppGoods> queryWrapper = new QueryWrapper();
        queryWrapper.ne("item_top", 3).ne("item_top", 4)
                .ne("item_top", 2).ne("item_top", 5).ne("item_top", 6);
        queryWrapper.eq("fqcat", cid);
        if (sort.contentEquals("recommend")) {
//            queryWrapper.eq("recommend", 1);
            queryWrapper.orderByDesc("recommend");
        }
        if (sort.contentEquals("sales")) {
            queryWrapper.orderByDesc("itemsale");  //销量
        }
        queryWrapper.orderByDesc("update_time");
        Map map = new HashMap<>();
        Page<AppGoods> page = new Page(pageNum, pageSize);
        IPage<AppGoods> recommendGoods = appGoodsMapper.selectPage(page, queryWrapper);

        if (recommendGoods.getTotal() != 0 && recommendGoods.getRecords() != null) {
            List<AppGoodsVo> appGoodsVoList = getAppGoodsVo(userid, recommendGoods.getRecords(), null, channelUserId, null);
            if (appGoodsVoList.size() > 0 && appGoodsVoList != null) {
                if (sort.contains("price_asc")) {
                    Collections.sort(appGoodsVoList);
                }
                if (sort.contains("price_desc")) {
                    Collections.sort(appGoodsVoList);
                    Collections.reverse(appGoodsVoList);
                }
            }
            map.put("min_id", null);
            map.put("data", appGoodsVoList);
            log.info("查询商品列表成功", appGoodsVoList);
            return ServerResponse.createBySuccess("数据获取成功", map);
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "没有更多商品");
        }
    }

    //获取商品列表
    @Override
    public ServerResponse getClassifyGoodsListNew(Integer pageSize, Integer pageNum, Integer cid, String
            sort, Integer
                                                          type, Long userid, String channelUserId, String version) {
        log.info("查询商品列表", "pageSize:" + pageSize, "pageNum:" + pageNum, "cid:" + cid, "sort:" + sort, "type:" + type, "userid:" + userid);
        String key = "app_classify_" + cid;
//        String classifiyKey = "app_classifyGoodsLists_" + pageNum;
        List<AppGoods> goodsList = null;
        if (redisTemplateService.hasKey(key)) {
            Map<String, List> map = (Map) redisTemplateService.getObj(key);
            for (String keys : map.keySet()) {
                if (keys.equals(pageNum.toString())) {
                    goodsList = map.get(keys);
                    break;
                }
            }

        } else {
            QueryWrapper<AppGoods> queryWrapper = new QueryWrapper();
            queryWrapper.eq("item_top", 1);
            queryWrapper.eq("fqcat", cid);
            queryWrapper.orderByAsc("sort");
            Page<AppGoods> page = new Page(pageNum, pageSize);
            IPage<AppGoods> recommendGoods = appGoodsMapper.selectPage(page, queryWrapper);
            if (recommendGoods.getTotal() != 0 && recommendGoods.getRecords() != null) {
                goodsList = recommendGoods.getRecords();

            }
        }
        if (goodsList != null && goodsList.size() > 0) {
            List<AppGoodsVo> appGoodsVoList = getAppGoodsVo(userid, goodsList, null, channelUserId, version);

            HashMap map = new HashMap<>();
            map.put("min_id", null);
            map.put("data", appGoodsVoList);
            log.info("查询商品列表成功", appGoodsVoList);
            return ServerResponse.createBySuccess("数据获取成功", map);
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "没有更多商品");
        }
    }

    /**
     * 大淘客热搜词
     *
     * @return
     */
    @Override
    public ServerResponse dtkHotSearch() {
        TreeMap<String, String> paraMap = new TreeMap<>();
        paraMap.put("version", "v1.0.1");
        paraMap.put("appKey", DaTaoKeConfig.DaTaoKe_CATEGORY_APPKEY);
        paraMap.put("sign", SignMD5Util.getSignStr(paraMap, DaTaoKeConfig.DaTaoKe_CATEGORY_APPSECRET));
        DaTaoKeHotWordsInfo daTaoKeResponse = null;
        try {
            String result = DtkHttpUtils.sendGet(DaTaoKeConfig.DaTaoKe_HOTSEARCH_URL, paraMap);
            daTaoKeResponse = JSON.parseObject(result, DaTaoKeHotWordsInfo.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<KeyWord> words = new ArrayList<KeyWord>();
        if (daTaoKeResponse != null && daTaoKeResponse.getCode() == 0 && daTaoKeResponse.getData() != null) {
            if (daTaoKeResponse.getData().getHotWords().size() > 15) {
                for (int i = 0; i <= 15; i++) {
                    KeyWord keyWord = new KeyWord();
                    keyWord.setKeyword(daTaoKeResponse.getData().getHotWords().get(i));
                    words.add(keyWord);
                }
//                words.get(1).setType(1);
//                words.get(2).setType(1);
//                words.get(6).setType(1);
//                words.get(9).setType(1);
//                words.get(14).setType(1);
            } else {
                for (int i = 0; i <= daTaoKeResponse.getData().getHotWords().size() - 1; i++) {
                    KeyWord keyWord = new KeyWord();
                    keyWord.setKeyword(daTaoKeResponse.getData().getHotWords().get(i));
                    words.add(keyWord);
                }

            }
            words.get(1).setType(1);
            words.get(2).setType(1);
            words.get(6).setType(1);
            words.get(words.size() - 6).setType(1);
            words.get(words.size() - 2).setType(1);
            return ServerResponse.createBySuccess("数据获取成功", words);
//            for (int i = 0; i <= 16; i++) {
//                hotWordsList.add(daTaoKeResponse.getData().get(0).getHotWords().get(i));
//            }
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");
        }
    }

    @Override
    public List<AppGoodsVo> getAppGoodsVo(Long userid, List<AppGoods> goods, ResponeResults results, String
            channelUserId, String version) {
        if (results == null) {
            results = goodsScheme(userid, goods, channelUserId);
        }
        String[] ignoreProperties = new String[]{"freeShipment", "itemDetail", "couponUrl", "couponStartTime", "couponEndTime", "shopId", "shopPicUrl", "shopTag", "shopUrl", "eval"};
        List<AppGoodsVo> appGoodsVoList = new ArrayList<>();
        if (results.getData() != null) {
            for (ResponeResults.DataBean dataBean : results.getData()) {
                if (!StringUtils.isEmpty(dataBean.getItemPrice())) {
                    int aa = 0;
                    int a = dataBean.getItemPrice().endsWith("0") ? 1 : 0;
                    int b = dataBean.getItemPrice().endsWith(".0") ? 2 : 0;
                    int c = dataBean.getItemPrice().endsWith(".00") ? 3 : 0;
                    int i = dataBean.getItemPrice().indexOf(".");
                    if (c > 0) {
                        aa = c;
                    } else if (b > 0) {
                        aa = b;
                    } else if (a > 0) {
                        aa = a;
                    }
                    if (aa > 0 && i > -1) {
                        String price = dataBean.getItemPrice().substring(0, dataBean.getItemPrice().length() - aa);
                        dataBean.setItemPrice(price);
                    }
//                    Boolean a = dataBean.getItemPrice().endsWith("0");
//                    boolean b = dataBean.getItemPrice().endsWith(".00");
//                    int i = dataBean.getItemPrice().indexOf(".");
//                    if ((a || b) && i > -1) {
//                        String price = dataBean.getItemPrice().substring(0, dataBean.getItemPrice().length() - (b ? 3 : 1));
//                        dataBean.setItemPrice(price);
//                    }
                }
                AppGoodsVo appGoodsVo = new AppGoodsVo();
                BeanUtils.copyProperties(dataBean, appGoodsVo, ignoreProperties);
                long sysTime = System.currentTimeMillis();
                if (com.eco.fanliapp.utils.StringUtils.isNotNull(dataBean.getActivityType())) {
                    if (!dataBean.getActivityType().contains("普通活动")) {
                        if (Long.valueOf((dataBean.getStartTime() == null || "".equals(dataBean.getStartTime()) || dataBean.getStartTime().indexOf("null") > -1) ? "0" : dataBean.getStartTime()) > sysTime) {
                            appGoodsVo.setStartTime(String.valueOf(Long.valueOf(dataBean.getStartTime() == null ? "" : dataBean.getStartTime()) - sysTime));
                            appGoodsVo.setEndTime(null);
                            appGoodsVo.setReceiveNum("0");
                        } else {
                            appGoodsVo.setStartTime(null);
                            if (Long.valueOf((dataBean.getEndTime() == null || "".equals(dataBean.getEndTime()) || dataBean.getEndTime().indexOf("null") > -1) ? "0" : dataBean.getEndTime()) > sysTime) {
                                appGoodsVo.setEndTime(String.valueOf(Long.valueOf(dataBean.getEndTime() == null ? "0" : dataBean.getEndTime()) - sysTime));
                                if (dataBean.getCouponnum() == "0" || dataBean.getCouponnum() == null) {
                                    appGoodsVo.setReceiveNum("100");
                                } else if (dataBean.getCouponreceive() == "0" || dataBean.getCouponreceive() == null) {
                                    appGoodsVo.setReceiveNum("0");
                                } else {
//                                    if (com.eco.fanliapp.utils.StringUtils.isNotNull(dataBean.getCouponnum())) {
//                                        appGoodsVo.setReceiveNum(BigDecimalUtils.FormatNum(dataBean.getCouponreceive(), dataBean.getCouponnum()));
//                                    }
                                }
                            } else {
                                appGoodsVo.setEndTime(null);
                                appGoodsVo.setActivityType(null);
                            }
                        }
                    } else {
                        appGoodsVo.setStartTime(null);
                        appGoodsVo.setEndTime(null);
                        appGoodsVo.setActivityType(null);
                    }
                } else {

                    appGoodsVo.setStartTime(null);
                    appGoodsVo.setEndTime(null);
                    appGoodsVo.setActivityType(null);
                }

                if (!StringUtils.isEmpty(version)) {
                    appGoodsVo.setCouponStartTime(dataBean.getCouponStartTime());
                    appGoodsVo.setCouponEndTime(dataBean.getCouponEndTime());
                } else {
                    //优惠卷时间
                    if (Long.valueOf((dataBean.getCouponStartTime() == null || "".equals(dataBean.getCouponStartTime()) || dataBean.getCouponStartTime().indexOf("null") > -1) ? "0" : dataBean.getCouponStartTime()) > sysTime) {
                        appGoodsVo.setCouponStartTime(String.valueOf(Long.valueOf(dataBean.getCouponStartTime() == null ? "" : dataBean.getCouponStartTime()) - sysTime));
                        appGoodsVo.setCouponEndTime(null);
                    } else {
                        appGoodsVo.setCouponStartTime(null);
                        if (Long.valueOf((dataBean.getCouponEndTime() == null || "".equals(dataBean.getCouponEndTime()) || dataBean.getCouponEndTime().indexOf("null") > -1) ? "0" : dataBean.getCouponEndTime()) > sysTime) {
                            appGoodsVo.setCouponEndTime(String.valueOf(Long.valueOf(dataBean.getCouponEndTime() == null ? "0" : dataBean.getCouponEndTime()) - sysTime));
                        } else {
                            appGoodsVo.setCouponEndTime(null);
                        }
                    }
                }

                if (com.eco.fanliapp.utils.StringUtils.isNotNull(appGoodsVo.getVideoid())) {
                    if (Long.parseLong(appGoodsVo.getVideoid()) > 0L) {
                        appGoodsVo.setVideoid("http://cloud.video.taobao.com/play/u/1/p/1/e/6/t/1/" + appGoodsVo.getVideoid() + ".mp4");
                    }
                } else {
                    appGoodsVo.setVideoid("0");
                }
                appGoodsVoList.add(appGoodsVo);
            }
        }
        return appGoodsVoList;
    }


    @Override
    public ResponeResults goodsScheme(Long userId, List<AppGoods> goods, String channelUserId) {
        AppUser user = null;
        AppCompany appCompany = null;
        AppOrderFeeScheme orderFeeScheme = null;
        AppGeneralFeeScheme generalFeeScheme = null;
        if (userId != null && userId != 0) {
            user = iAppUserService.selectAppUserByUserId(userId, 1);
            appCompany = iAppCompanyService.findtAppCompany(user == null ? null : user.getCompanyId(), 1);
        }
        if (appCompany == null) {
            appCompany = iAppCompanyService.findtAppCompany(null, 1);
        }
        //杀熟分佣
//        orderFeeScheme = appCompany.getOrderFeeScheme();
        //普通分佣
        generalFeeScheme = appCompany.getGeneralFeeScheme();

        List<SyChannelGoods> syChannelGoodsAll = syChannelGoodsService.getAllAppChannelGoods(1);

        ResponeResults results = new ResponeResults();
        List<ResponeResults.DataBean> beans = new ArrayList<ResponeResults.DataBean>();
        if (goods != null) {
            for (AppGoods dataBean : goods) {
                if (dataBean != null) {
                    String fixedCommissionType = null;
                    //获取高佣商品固定返
                    fixedCommissionType = taoBaoMethodService.getFixedCommission(dataBean.getItemid(), userId, fixedCommissionType, syChannelGoodsAll);

                    ResponeResults.DataBean bean = new ResponeResults.DataBean();
                    bean.setActivityId(dataBean.getActivityid());
                    bean.setSort(dataBean.getSort());
                    bean.setMsg(dataBean.getMsg());
                    bean.setLabelName(dataBean.getLabelName());
                    bean.setVideoid(dataBean.getVideoid() == null ? "0" : dataBean.getVideoid());
                    bean.setActivityType(dataBean.getActivityType() == null ? "" : dataBean.getActivityType());
                    bean.setStartTime(dataBean.getStartTime() == null ? "0" : dataBean.getStartTime());
                    bean.setEndTime(dataBean.getEndTime() == null ? "0" : dataBean.getEndTime());
                    bean.setCouponreceive(dataBean.getCouponreceive() == null ? "0" : dataBean.getCouponreceive());
                    bean.setCouponnum(dataBean.getCouponnum() == null ? "0" : dataBean.getCouponnum());
                    bean.setItemId(dataBean.getItemid() == null ? "" : dataBean.getItemid());
                    bean.setItemTitle(dataBean.getItemtitle() == null ? "" : dataBean.getItemtitle());
                    bean.setItemShortTitle(dataBean.getItemshorttitle() == null ? "" : dataBean.getItemshorttitle());
                    bean.setItemPrice(dataBean.getItemprice() == null ? "0" : dataBean.getItemprice());
                    bean.setItempictUrl(dataBean.getItempic() == null ? "" : dataBean.getItempic());
                    bean.setLableUrl(dataBean.getLableUrl() == null ? null : dataBean.getLableUrl());
                    if (bean.getItempictUrl() != null) {
//                    bean.setItempictUrl(bean.getItempictUrl().replaceAll(".jpg", ".jpg_200x200.jpg"));
                    }
                    bean.setItemSmallImages(dataBean.getTaobaoImage() == null ? dataBean.getTaobaoImage() : dataBean.getTaobaoImage().replace(" ", ""));
                    if (bean.getItemSmallImages() != null && bean.getItemSmallImages().split(",").length > 0) {
//                    bean.setItemSmallImagesFirst(bean.getItemSmallImages().split(",")[0].replaceAll(".jpg", ".jpg_200x200.jpg"));
                        bean.setItemSmallImagesFirst(bean.getItemSmallImages().split(",")[0]);
                    } else {
                        if (bean.getItempictUrl() != null) {
                            bean.setItemSmallImagesFirst(bean.getItempictUrl());
                        }
                    }
                    bean.setCouponUrl(dataBean.getCouponurl() == null ? "" : dataBean.getCouponurl());
                    bean.setCouponStartTime(dataBean.getCouponstarttime() == null ? "0" : dataBean.getCouponstarttime());
                    bean.setCouponEndTime(dataBean.getCouponendtime() == null ? "0" : dataBean.getCouponendtime());
//                bean.setFreeShipment(true);
//                if ("B".equals(dataBean.getShoptype())) {
//                    bean.setItemType(dataBean.getShoptype());
//                } else if ("C".equals(dataBean.getShoptype())) {
//                    bean.setItemType(dataBean.getShoptype());
//                } else {
//                    bean.setItemType(dataBean.getItemType() == null ? "" : dataBean.getItemType().toString());
//                }

                    bean.setItemType(dataBean.getShoptype() == null ? "" : dataBean.getShoptype());
                    bean.setItemSale(String.valueOf(dataBean.getItemsale() == null ? "0" : dataBean.getItemsale()));
                    bean.setCouponMoney(BigDecimalUtils.Format(dataBean.getCouponmoney()).intValue());
                    bean.setHasCoupon(bean.getCouponMoney() == null ? false : true);
                    bean.setShopName(dataBean.getShopname() == null ? "" : dataBean.getShopname());
                    bean.setShopId(dataBean.getShopid() == null ? "0" : dataBean.getShopid());
                    WeiYiInfo info = JsonUtils.getJsonToBean(dataBean.getWyItemDetail(), WeiYiInfo.class);
                    if (info != null) {
                        bean.setShopPicUrl(info.getData().getSeller().getShopIcon() == null ? "" : "https" + info.getData().getSeller().getShopIcon());
                        bean.setShopTag(info.getData().getSeller().getTagIcon() == null ? "" : info.getData().getSeller().getTagIcon());
                        bean.setShopUrl(info.getData().getSeller().getTaoShopUrl() == null ? "" : "https" + info.getData().getSeller().getTaoShopUrl());
                        bean.setItemDetail(info.getData().getItem_detail());
                        bean.setEval(info.getData().getSeller().getEvaluates());
                    }

                    Integer s = null;
                    if (null != userId && 0 != userId) {
                        if (user != null && user.getEnable() == 0) {//禁用
                            BigDecimal fl = BigDecimalUtils.Format("0");
                            BigDecimal flh = BigDecimalUtils.Format(dataBean.getItemendprice() == null ? 0d : dataBean.getItemendprice());
                            bean.setFanliMoney(fl);
                            bean.setFanlihoMoney(flh);
                            bean.setTheirPriceMoney(flh.subtract(fl));
                        } else {
                            s = taoBaoMethodService.getCommissionRate(appCompany, orderFeeScheme, generalFeeScheme, userId, Double.valueOf(dataBean.getTkmoney() == null ? "0" : dataBean.getTkmoney()));
                        }
                    } else {
                        s = taoBaoMethodService.getCommissionRate(appCompany, orderFeeScheme, generalFeeScheme, userId, Double.valueOf(dataBean.getTkmoney() == null ? "0" : dataBean.getTkmoney()));
                    }

                    if (fixedCommissionType == null) {
                        BigDecimal fl = BigDecimalUtils.FanliMoney(s.toString(), BigDecimalUtils.Format(dataBean.getTkmoney() == null ? "0" : dataBean.getTkmoney()));
                        BigDecimal flh = BigDecimalUtils.Format(dataBean.getItemendprice() == null ? 0d : dataBean.getItemendprice());
                        bean.setFanliMoney(fl);
                        bean.setFanlihoMoney(flh);
                        bean.setTheirPriceMoney(flh.subtract(fl));
                        bean.setItemTop(dataBean.getItemTop() == null ? 1 : dataBean.getItemTop());
                        bean.setSpareMoney(fl.add(new BigDecimal(bean.getCouponMoney() == null ? 0 : bean.getCouponMoney())));
                    } else {
                        BigDecimal flh = BigDecimalUtils.Format(Double.valueOf(dataBean.getItemendprice()));
                        bean.setFanliMoney(new BigDecimal(fixedCommissionType));
                        bean.setFanlihoMoney(flh);
                        bean.setTheirPriceMoney(flh.subtract(new BigDecimal(fixedCommissionType)));
                        bean.setItemTop(dataBean.getItemTop() == null ? 1 : dataBean.getItemTop());
                        bean.setSpareMoney(new BigDecimal(fixedCommissionType).add(new BigDecimal(bean.getCouponMoney() == null ? 0 : bean.getCouponMoney())));

                    }
                    beans.add(bean);
                }
            }
        }
        results.setData(beans);
        return results;
    }

    private static String taoKouLing(String str) {
        String[] specialCharacters = {"《", "￥", "£", "$", "€", "₤", "¢", "₴", "₰", "(", ")", "₳"};
        try {
            for (int i = 0; i < specialCharacters.length; i++) {
                String oneSpecialCharacters = specialCharacters[i];
                if ("《".equals(oneSpecialCharacters) && str.contains(oneSpecialCharacters)) {
                    return str.substring(str.indexOf("《") + 1, str.indexOf("》"));
                } else if ("￥".equals(oneSpecialCharacters) && str.contains(oneSpecialCharacters)) {
                    return str.substring(str.indexOf("￥") + 1, str.lastIndexOf("￥"));
                } else if ("(".equals(oneSpecialCharacters) && str.contains(oneSpecialCharacters)) {
                    return str.substring(str.indexOf("(") + 1, str.indexOf(")"));
                } else if ("$".equals(oneSpecialCharacters) && str.contains(oneSpecialCharacters)) {
                    return str.substring(str.indexOf("$") + 1, str.lastIndexOf("$"));
                } else if (str.contains(oneSpecialCharacters)) {
                    return RegUtils.getreGex(str, "" + oneSpecialCharacters + "([a-zA-Z0-9]{11})" + oneSpecialCharacters + "").replace(oneSpecialCharacters, "");
                }
            }
        } catch (Exception e) {
            log.info("淘口令识别错误：" + str);
            return taoKouLing2(str);
        }
        return "";
    }

    /**
     * 截取淘口令
     *
     * @param href
     * @return
     */
    public static String getTbInnerCode(String href) {
        String strAfter = Pattern.compile("\\s*|\t|\r|\n").matcher(href).replaceAll("");
        String pattern = ".*([(￥€$₤₳¢¤฿฿₵₡₫ƒ₲₭£₥₦₱〒₮₩₴₪៛﷼₢ℳ₰₯₠₣₧ƒ￡][a-z0-9A-Z]{9,11}[)￥€$₤₳¢¤฿฿₵₡₫ƒ₲₭£₥₦₱〒₮₩₴₪៛﷼₢ℳ₰₯₠₣₧ƒ￡]).*";
        boolean isMatch = Pattern.matches(pattern, strAfter);
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(strAfter);

        if (isMatch && m.find()) {
            return m.group(1);
        }

        return null;
    }

    public static void main(String[] args) {
        String href = "【情侣棉拖鞋女冬季可爱室内居家保暖鞋防滑厚底家用韩版毛毛拖鞋男】https://m.tb.cn/h.eyDiMvf?sm=402720 嚸↑↓擊鏈バ接，再选择瀏覽→噐咑ぺ鐦；或椱ァ製这句话$rvNnYAvdZ3M$后咑閞\uD83D\uDC49綯℡寳\uD83D\uDC48";
    }

    private static String taoKouLing2(String str) {
        try {
            String regEx = "([a-zA-Z0-9]{11})";
            Matcher matcher = Pattern.compile(regEx).matcher(str);
            String tkl = "";
            while (matcher.find()) {
                tkl = matcher.group(0);
            }
            return tkl;
        } catch (Exception e) {
            log.info("淘口令识别错误：" + str);
            return "";
        }
    }

    /**
     * 通过商品id和用户id查询计算商品的佣金
     *
     * @param userId
     * @return
     */
    @Override
    public List<SyTimePeriodGoods> calculatedGoodsCommission(Long
                                                                     userId, List<SyTimePeriodGoods> syTimePeriodGoodsList) {
        AppUser user = null;
        AppCompany appCompany = null;
        AppOrderFeeScheme orderFeeScheme = null;
        AppGeneralFeeScheme generalFeeScheme = null;
        if (userId != null && userId != 0) {
            user = appUserMapper.selectAppUserByUserId(userId);
            appCompany = iAppCompanyService.findtAppCompany(userId);
        }
        if (appCompany == null) {
            appCompany = iAppCompanyService.findCompanyAll();
        }
        //杀熟分佣
        orderFeeScheme = appCompany.getOrderFeeScheme();
        //普通分佣
        generalFeeScheme = appCompany.getGeneralFeeScheme();

        List<SyTimePeriodGoods> syTimePeriodGoodsListNew = new ArrayList<>();

        if ((!StringUtils.isEmpty(user) && user.getEnable() == 1) || StringUtils.isEmpty(user)) {
            if (syTimePeriodGoodsList != null) {
                for (SyTimePeriodGoods syTimePeriodGoods : syTimePeriodGoodsList) {
                    Integer s = taoBaoMethodService.getCommissionRate(appCompany, orderFeeScheme, generalFeeScheme, userId, Double.valueOf(syTimePeriodGoods.getTkMoney() == null ? "0" : syTimePeriodGoods.getTkMoney().toString()));
                    BigDecimal fl = BigDecimalUtils.FanliMoney(s.toString(), BigDecimalUtils.Format(syTimePeriodGoods.getTkMoney() == null ? new BigDecimal("0") : syTimePeriodGoods.getTkMoney()));
                    //到手价
                    syTimePeriodGoods.setTheirPriceMoney(syTimePeriodGoods.getDiscountPrice().subtract(fl));
                    //修改折扣价，改成到手价格
                    syTimePeriodGoods.setDiscountPrice(syTimePeriodGoods.getDiscountPrice().subtract(fl));

                    if (syTimePeriodGoods.getDiscountPrice().doubleValue() >= 0) {
                        syTimePeriodGoodsListNew.add(syTimePeriodGoods);
//                        syTimePeriodGoodsList.remove(syTimePeriodGoods);
//                        iSyTimePeriodGoodsService.removeById(syTimePeriodGoods.getTableId());
                    }
                }
            }
        }
        return syTimePeriodGoodsListNew;
    }

    @Override
    public void getRedisRecommendGoodsList(List<AppGoods> appGoodsList) {
//
//        appGoodsList = appGoodsMapper.selectRecommendGoodsAll();
//        List<AppGoods> tljAppGoods = appGoodsMapper.selectTljGoods();
        List<AppGoods> channelAppGoods = appGoodsMapper.selectChannelGoods();
        List<AppGoods> newList = new ArrayList<>();
//        if (tljAppGoods != null) {
//            newList.addAll(tljAppGoods);
//        }
        if (channelAppGoods != null) {
            newList.addAll(channelAppGoods);
        }
        redisTemplateService.set("app_tlj_channel_count", newList.size(), 0);
        String fixedSort_key = "app_fixedSortGoods_list";
        if (redisTemplateService.hasKey(fixedSort_key)) {
            Map<String, Integer> fixedSortMap = redisTemplateService.getMap(fixedSort_key, Map.class);
            for (String sortKey : fixedSortMap.keySet()) {
                AppGoods appGoods = appGoodsMapper.findAppGoodsByItemId(sortKey);
                for (int i = 0; i <= appGoodsList.size() - 1; i++) {
                    if (appGoodsList.get(i).getItemid().equals(sortKey)) {
                        appGoodsList.remove(appGoodsList.get(i));
                        break;
                    }
                }
                if (appGoods != null && appGoods.getDeleted() == 0) {
                    appGoodsList.add(fixedSortMap.get(sortKey) - 1, appGoods);
                }
            }
        }
        //加标签
        Map<String, Object> stringObjectMap = goodsImageLableService.selectGoodsImageLable();
        if (stringObjectMap != null) {
            if (stringObjectMap.containsKey("festivalLable") && stringObjectMap.containsKey("festivalSeckill")) {
                int num = 0;
                for (int i = 0; i < appGoodsList.size(); i++) {
                    if (i == num && i < 80) {
                        appGoodsList.get(i).setLableUrl(stringObjectMap.get("festivalSeckill").toString());
                        num += 5;
                    } else {
                        appGoodsList.get(i).setLableUrl(stringObjectMap.get("festivalLable").toString());
                    }
                }
                if (newList != null && newList.size() > 0) {
                    for (AppGoods appGoods : newList) {
                        appGoods.setLableUrl(stringObjectMap.get("festivalSeckill").toString());
                    }
                }

            } else if (stringObjectMap.containsKey("commonLable") && stringObjectMap.containsKey("commonSeckill")) {
                int num = 0;
                for (int i = 0; i < appGoodsList.size(); i++) {
                    if (i == num && i < 80) {
                        appGoodsList.get(i).setLableUrl(stringObjectMap.get("commonSeckill").toString());
                        num += 5;
                    } else {
                        appGoodsList.get(i).setLableUrl(stringObjectMap.get("commonLable").toString());
                    }
                }
                if (newList != null && newList.size() > 0) {
                    for (AppGoods appGoods : newList) {
                        appGoods.setLableUrl(stringObjectMap.get("commonSeckill").toString());
                    }
                }
            }
        }
        //淘礼金+单个高佣+首页推荐排序
        newList.addAll(appGoodsList);

        int mo = newList.size() % 40;
        int pageNum = newList.size() / 40;
        int pageSize = 40;
        if (mo > 0) {
            pageNum += 1;
        }
        if (newList != null && newList.size() > 0) {
            for (int i = 1; i <= pageNum; i++) {
                List<AppGoods> pageAppGoodsList = new ArrayList<>();
                int currIdx = (i > 1 ? (i - 1) * pageSize : 0);
                for (int y = 0; y < pageSize && y <= newList.size() - currIdx - 1; y++) {
                    AppGoods appGoods = newList.get(currIdx + y);
                    pageAppGoodsList.add(appGoods);
                }
                String key = "app_recommendGoodsLists_" + i;
                redisTemplateService.set(key, pageAppGoodsList, 0);
            }
        }
    }
//    String recommendRedisKey = "recommend_goods_list_and_tji_channel";
//    List<AppGoods> goodsList1 = new ArrayList<>();
//        if(redisTemplateService.hasKey(recommendRedisKey)){
//        goodsList1 = redisTemplateService.getTByListKey(recommendRedisKey, AppGoods.class);
//    }
//        if(goodsList1 == null || goodsList1.size() <= 0){
//        //首页推荐商品
//        List<AppGoods> recommendGoods = appGoodsMapper.selectRecommendGoodsAll();
//        //添加图片标签 0 5 10 15...
//        Map<String, Object> stringObjectMap = goodsImageLableService.selectGoodsImageLable();
//        if(stringObjectMap != null){
//            if(stringObjectMap.containsKey("festivalLable") && stringObjectMap.containsKey("festivalSeckill")){
//                int num = 0;
//                for(int i = 0;i < recommendGoods.size();i++){
//                    if(i == num && i <= 145){
//                        recommendGoods.get(i).setLableUrl(stringObjectMap.get("festivalSeckill").toString());
//                        num+=5;
//                    }else {
//                        recommendGoods.get(i).setLableUrl(stringObjectMap.get("festivalLable").toString());
//                    }
//                }
//            }else if(stringObjectMap.containsKey("commonLable") && stringObjectMap.containsKey("commonSeckill")){
//                int num = 0;
//                for(int i = 0;i < recommendGoods.size();i++){
//                    if(i == num && i <= 145){
//                        recommendGoods.get(i).setLableUrl(stringObjectMap.get("commonSeckill").toString());
//                        num+=5;
//                    }else {
//                        recommendGoods.get(i).setLableUrl(stringObjectMap.get("commonLable").toString());
//                    }
//                }
//            }
//        }
//        if(recommendGoods != null && recommendGoods.size() > 0){
//            String fixedSort_key = "app_fixedSortGoods_list";
//            if (redisTemplateService.hasKey(fixedSort_key)) {
//                Map<String, Integer> fixedSortMap = redisTemplateService.getMap(fixedSort_key, Map.class);
//                for (String sortKey : fixedSortMap.keySet()) {
//                    AppGoods appGoods = appGoodsMapper.findAppGoodsByItemId(sortKey);
//                    for (int i = 0; i <= recommendGoods.size() - 1; i++) {
//                        if (recommendGoods.get(i).getItemid().equals(sortKey)) {
//                            recommendGoods.remove(recommendGoods.get(i));
//                        }
//                    }
//                    if (appGoods != null){
//                        recommendGoods.add(fixedSortMap.get(sortKey) - 1, appGoods);
//                    }
//
//                }
//            }
//        }
//        //淘礼金等置顶
//        List<AppGoods> itemtopAppGoods = appGoodsMapper.selectItemtopAll();
//        if(itemtopAppGoods != null){
//            goodsList1.addAll(itemtopAppGoods);
//        }
//        goodsList1.addAll(recommendGoods);
//        redisTemplateService.set(recommendRedisKey,goodsList1,60*5);
//    }
//    //分页后新list
//    List<AppGoods> pageAppGoodsList = new ArrayList<>();
//        if(goodsList1 != null && goodsList1.size() > 0){
//        int currIdx = (pageNum > 1 ? (pageNum -1) * pageSize : 0);
//        for (int i = 0; i < pageSize && i < goodsList1.size() - currIdx; i++) {
//            AppGoods appGoods = goodsList1.get(currIdx + i);
//            pageAppGoodsList.add(appGoods);
//        }
//    }

}
